Not proficient with C++, I am trying to implement stack using C++ classes and here's my code.
#include <iostream>
#include <string>
using namespace std;
class myStackElement {
private:
string Data;
myStackElement* prev;
public:
myStackElement(string myData, myStackElement* head) {
Data = myData;
prev = head;
}
string popped(myStackElement* head) {
head = prev;
return Data;
}
string top() {
return Data;
}
};
class myStack {
private:
myStackElement* head;
public:
myStack() {
head = NULL;
}
void push(string myData) {
myStackElement* temp = new myStackElement(myData, head);
head = temp;
}
string pop() {
if(head == NULL) {
return "0";
}
else {
myStackElement * const temp = head;
string popped = head->popped(head);
delete temp;
return popped;
}
}
string peek() {
if(head == NULL) {
return "0";
}
else {
string top = head->top();
return top;
}
}
};
int main() {
myStack hello;
hello.push("other");
string top = hello.peek();
cout << top << endl;
hello.push("another");
top = hello.peek();
cout << top << endl;
string popped = hello.pop();
cout << popped << endl;
top = hello.peek();
cout << top << endl;
return 0;
}
the output is
other
another
another
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Aborted (core dumped)
Interesting thing is that if I don't peek
after popping
, the code works fine (prints first three lines). So, I think my head
pointer is getting messed up after popping.
It may be related to wrong usage of delete
operator. But, I haven't used them enough to know.
The code above is first attempt.
Thanks in advance.
As discusses in comments, the head pointer is not being updated in popped function to change a pointer I need to pass a pointer or reference to that pointer.
string popped(myStackElement** head) {
*head = prev;
return Data;
}
and
string pop() {
if(head == NULL) {
return "0";
}
else {
myStackElement * const temp = head;
string popped = head->popped(&head);
delete temp;
return popped;
}
}