int Stack::pop(NODE *head)
{
cout<<"In pop"<<endl;
if(head == NULL)
{
cout<<"No data in head available"<<endl;
return (int)NULL;
}
else
{
NODE *temp=NULL;
//Point the temp node to the linked list
temp = head;
//move head to the next node
head = head->next;
int num = temp->data;
//make sure temp is not pointing to next element so that we can free it
temp->next = NULL;
delete temp;
return num;
}
}
Now the issue is, when I call pop for the first time, item is popped but when I call the pop for second time, a glitch is detected.
First, you don't need to initialize temp to NULL if you are gonna assign something else to it in the very next operation, so instead of
1 2 3
NODE *temp=NULL;
//Point the temp node to the linked list
temp = head;
make NODE *temp=head
Also, when you return (int)NULL, it shows you don't know what you're doing, becouse somewhere in the compiler, there is a #define NULL 0 !
Yes, the algorithm is wrong too! You don't erase the head, but the tail! What you made is a queue! with a list 5-> 4-> 3-> 2-> 1->NULL, 1 should be erased, becouse it is the last item put in!
I thought its always a good practice to take a initial pointer as NULL to avoid any dangling pointers or other error.
It is but in your case you're able to set "temp" to a valid pointer on initialization, so you might as well. Basically you just don't want your pointer initialized to garbage.
I notice you're sending the head in to the function, is it changed to be head->next after the first pop call? Usually the internal structures of data structures are hidden to users, but in your case it looks like it's visible.
I would recommend having NODE* head as a private variable inside the class and not having any arguments when calling pop
thanks for making my day.........i needed to use a double pointer for passing head to pop function so that the new head in main function could be updated.