Implement PUSH, POP, and TRAVERSE operations on a stack using linked list.
#include <stdio.h>
#include <stdlib.h>
struct Stack
{
int value;
struct Stack *next;
} *top;
void push(int n){
struct Stack * newNode = (struct Stack *) malloc(sizeof(struct Stack));
newNode->value = n;
newNode->next = top;
top = newNode;
}
int pop()
{
int data = 0;
struct Stack * topNode;
if (!top)
{
printf("Stack is empty.\n");
return -1;
}
topNode = top;
data = top->value;
top = top->next;
free(topNode);
return data;
}
void traverse(){
if(!top){
printf("List is empty!\n");
return;
}else{
struct Stack * topNode=top;
printf("\nAll values in stack:\n");
while(topNode!=NULL){
printf("%d\n",topNode->value);
topNode=topNode->next;
}
printf("\n\n");
}
}
int main()
{
printf("push: 45\n");
push(45);
printf("push: 5\n");
push(5);
printf("push: 2\n");
push(2);
printf("push: 10\n");
push(10);
printf("push: 20\n");
push(20);
traverse();
printf("pop: %d\n",pop());
printf("pop: %d\n",pop());
traverse();
free(top);
getchar();
getchar();
return 0;
}
Comments
Leave a comment