having issue with stack using linked list.
1) the num didnt give any value tho with the cout in count()
2) how to return string from pop()? i tried many ways like return ptr->s and stuff but didnt work
could anyone pls point out where my mistake is? thanks heaps!
header file
Code:
class Element{
public:
std::string s;
Element *next;
};
Element * start = NULL;
class Stack {
public:
//temporary pointer
Element * ptr, *ptr2;
unsigned long num;
Stack();
~Stack();
void push(std::string n);
unsigned long count();
std::string pop();
};
cpp.file
Code:
#include <iostream>
#include <string>
#include <stdlib.h>
#include "stack.h"
using namespace std;
Stack::Stack(){
num = 0;
}
void Stack :: push(std::string n){
ptr = new Element; //create space
ptr->s = n; // pointing at string
ptr->next = NULL;
if (start == NULL){ //empty
start = ptr;} //ptr and start pointing at the same spot
else{ //if start already has element
ptr2 = start;
while (ptr2->next != NULL){
ptr2 = ptr2->next; // keep moving to next element
}
//if next element is null,add new element
ptr2->next = ptr;
num++;
}
/*cout << ptr->s << endl;*/
}
std:: string Stack::pop(){
//pop until stack is empty
std::string n2 = ptr->s ;
if ( start != NULL ){
ptr = start;
//if next element where ptr is pointing is null,delete current ptr
if (ptr->next == NULL){
delete ptr;
start = NULL;
}
else {
while (ptr->next != NULL){
ptr2 = ptr;
ptr = ptr->next;}
delete ptr;
ptr2->next = NULL;
}
num--;
}
cout << n2 << endl;
return n2;
}
unsigned long Stack::count(){
cout << num;
return num;
}
Stack :: ~Stack () {
while (start != NULL){
Element* temp = start;
start = start->next;
delete temp;
}
}
int main(){
Stack s;
s.push("Hello");
s.push("world");
s.pop();
s.pop();
}