Stack using Singly Linked List
#include<stdio.h>
#include<stdlib.h>
struct
stack
{
int
data;
struct stack *link;
};
typedef struct stack * NODE;
NODE
top = NULL;
void
insert_front(int item);
NODE
delete_front();
void display();
NODE getnode()
{
NODE
x;
x
= (NODE)malloc(sizeof(struct stack));
x->link
= NULL;
}
void
insert_front(int item)
{
NODE
temp;
temp
= getnode();
temp->data
= item;
if(top
!= NULL)
{
temp->link
= top;
}
top
= temp;
}
NODE delete_front()
{
NODE
temp;
if(top
== NULL)
{
printf("\nStack
underflow");
return
NULL;
}
else
{
temp
= top;
top
= top->link;
printf("\nItem
got deleted is: %d", temp->data);
free(temp);
return
top;
}
}
void display()
{
NODE cur;
if(top
== NULL)
{
printf("\nStack
is empty");
}
else
{
printf("\nContents
are: \n");
cur = top;
while(cur!=NULL)
{
printf("|
%d |\n", cur->data);
cur
= cur->link;
}
}
}
void main()
{
int
ch, item;
while(1)
{
printf("\n~~MENU~~");
printf("\n1.Push
operation");
printf("\n2.Pop
operation");
printf("\n3.Display");
printf("\nEnter
your choice: ");
scanf("%d",
&ch);
switch(ch)
{
case
1: printf("\nEnter
the item to be inserted: ");
scanf("%d", &item);
insert_front(item);
display();
break;
case
2: top = delete_front();
display();
break;
case
3: display();
break;
case
4: exit(0);
}
}
}
Output:
~~MENU~~
1.Push operation
2.Pop operation
3.Display
Enter your choice: 1
Enter
the item to be inserted: 11
Contents
are:
|
11 |
~~MENU~~
1.Push operation
2.Pop operation
3.Display
Enter your choice: 1
Enter
the item to be inserted: 12
Contents
are:
|
12 |
|
11 |
~~MENU~~
1.Push operation
2.Pop operation
3.Display
Enter your choice: 1
Enter
the item to be inserted: 13
Contents
are:
|
13 |
|
12 |
|
11 |
~~MENU~~
1.Push operation
2.Pop operation
3.Display
Enter your choice: 1
Enter
the item to be inserted: 14
Contents
are:
|
14 |
|
13 |
|
12 |
|
11 |
~~MENU~~
1.Push operation
2.Pop operation
3.Display
Enter your choice: 2
Item
got deleted is: 14
Contents
are:
|
13 |
|
12 |
|
11 |
~~MENU~~
1.Push operation
2.Pop operation
3.Display
Enter your choice: 2
Item
got deleted is: 13
Contents
are:
|
12 |
|
11 |
~~MENU~~
1.Push operation
2.Pop operation
3.Display
Enter your choice: 2
Item
got deleted is: 12
Contents
are:
|
11 |
~~MENU~~
1.Push operation
2.Pop operation
3.Display
Enter your choice: 2
Item
got deleted is: 11
Stack
is empty
~~MENU~~
1.Push operation
2.Pop operation
3.Display
Enter your choice: 2
Stack
underflow
Stack
is empty
~~MENU~~
1.Push operation
2.Pop operation
3.Display
Enter your choice: 4
No comments:
Post a Comment