I’m trying to implement a stack in C using singly linked lists, it all works fine as long as the stack is non-empty. Once empty my pop method never detects that its empty but gives some random values. Is there any way so that i can know the stack is empty ? Here is the pop method i’m using along with a sample main program output.
int main(int argc, char const *argv[])
{
Node* top;
push(&top,5);
printf("Popped Element: %d\n",pop(&top));
printf("Popped Element: %d\n",pop(&top));
return 0;
}
int pop(Node** top)
{
if(*top == NULL)
{
printf("Error: Stack is empty!\n");
return;
}
int temp = (*top)->iData;
*top = (*top)->next;
return temp;
}
output:
Popped Element: 5
Popped Element: 1707388
EDIT:
here is the code for push
void push(Node** top ,int num)
{
Node* temp = (Node* )malloc(sizeof(Node));
temp->iData = num;
temp->next = *top;
*top = temp;
}
initialize next to NULL while creating and adding a new node to the list. and use
instead of
Edit:
Initialize *top =NULL in main like