C Program to implement Stacks using Singly Linked List
Program
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
int info;
struct node *link;
};
typedef struct node* NODE;
NODE getnode();
NODE push(NODE , int);
NODE pop(NODE);
void display(NODE);
void main()
{
NODE top;
int choice, item;
top = NULL;
while(1)
{
printf("Enter\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter item to be inserted\n");
scanf("%d", &item);
top = push(top, item);
break;
case 2:
top = pop(top);
break;
case 3:
display(top);
break;
default:
exit(0);
}
}
}
NODE getnode()
{
NODE x;
x = (NODE) malloc(sizeof(struct node));
if(x == NULL)
{
printf("Node creation error\n");
return;
}
return x;
}
NODE push(NODE top , int item)
{
NODE temp;
temp = getnode();
temp->info = item;
temp->link = top;
return temp;
}
NODE pop(NODE top)
{
NODE temp;
if(top == NULL)
{
printf("Stack underflow. Cannot pop\n");
return top;
}
temp = top;
top = top->link;
printf("Deleted item is %d\n", temp->info);
free(temp);
return top;
}
void display(NODE top)
{
NODE temp;
printf("Contents of stacks are:\n");
if(top == NULL)
{
printf("Cannot print. Empty stack\n");
return;
}
temp = top;
while(temp != NULL)
{
printf("%d\n", temp->info);
temp = temp->link;
}
printf("\n");
}
Output
Enter
1. Push
2. Pop
3. Display
4. Exit
2
Stack underflow. Cannot pop
Enter
1. Push
2. Pop
3. Display
4. Exit
1
Enter item to be inserted
30
Enter
1. Push
2. Pop
3. Display
4. Exit
1
Enter item to be inserted
41
Enter
1. Push
2. Pop
3. Display
4. Exit
1
Enter item to be inserted
22
Enter
1. Push
2. Pop
3. Display
4. Exit
1
Enter item to be inserted
3
Enter
1. Push
2. Pop
3. Display
4. Exit
3
Contents of stacks are:
3
22
41
30
Enter
1. Push
2. Pop
3. Display
4. Exit
1
Enter item to be inserted
32
Enter
1. Push
2. Pop
3. Display
4. Exit
3
Contents of stacks are:
32
3
22
41
30
Enter
1. Push
2. Pop
3. Display
4. Exit
2
Deleted item is 32
Enter
1. Push
2. Pop
3. Display
4. Exit
2
Deleted item is 3
Enter
1. Push
2. Pop
3. Display
4. Exit
3
Contents of stacks are:
22
41
30
Enter
1. Push
2. Pop
3. Display
4. Exit
4