I have really no idea why this is happening, I am accessing a member of class node.
The node's next
and prev
values by default are NULL
. The function where I am getting this error is Stack.push
when the control comes to the line where memory new node
is being allocated to the *node->next
, it gives error.
// question: Implement stacks using linked lists
#include <iostream>
using namespace std;
class node
{
public:
int data;
node *next = NULL;
node *prev = NULL;
};
class Stack
{
// LIFO : LAST IN FIRST OUT
node *top;
public:
void push(int data)
{
top->next = new node; // here ,getting a segmentation fault while debugging :(
top->next->prev = top;
top = top->next;
top->data = data;
}
int pop()
{
node *old_top = top;
top = top->prev;
delete old_top;
return top->data;
}
friend void print_Stack(Stack *s);
};
void print_Stack(Stack *s)
{
node* cur = s->top;
while(cur->prev != NULL)
{
printf("%d<", cur->data);
cur = cur->prev;
}
cout << cur->data << endl;
}
int main()
{
/* code */
Stack* S = new Stack;
int i = 10;
while (i--)
S->push(i);
print_Stack(S);
return 0;
}