My push function works fine, but when I pop the last integer entered into my stack, first the last integer changes to zero then if I pop it again it changes to some garbage integer (this is what is showing when running it in the console). I'm guessing it has to do something in pop() where I am not freeing the node correctly..
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node* next;
}Node;
Node* push(Node* root, int value){
Node* temp = malloc(sizeof(Node));
temp->data = value;
temp->next = NULL;
if(root == NULL){
root = temp;
}
else{
temp->next = root;
root = temp;
}
return root;
}
int pop(Node* root){
if(root == NULL){
printf("nothing to pop, stack is already empty.\n");
return -1;
}
Node* temp = root;
root = root->next;
int returnValue = temp->data;
free(temp);
return returnValue;
}
int peek(Node* root){
if(root == NULL){
printf("Stack is currently empty.\n");
return -1;
}
return root->data;
}
int isEmpty(Node* root){
if(root == NULL){
return 1;
}
return 0;
}
void display(Node* root){
printf("\n");
printf("List: ");
while(root != NULL){
printf("%d ", root->data);
root = root->next;
}
printf("\n\n");
}
int main(){
Node* root = NULL;
int data, choice;
printf("\n\nMenu: (1)Push (2)Pop (3)Exit\n\n");
while(1){
printf("Enter choice: ");
scanf("%d", &choice);
printf("\n");
if(choice == 1){
printf("Enter data to push: ");
scanf("%d", &data);
root = push(root, data);
display(root);
}
if(choice == 2){
pop(root);
display(root);
}
if(choice == 3){
break;
}
}
return 0;
}
Don't know where I'm going wrong!