Write a program in C for stack using linked list implementation.
Algorithm :
Step1: Define a C-struct for each node in the stack. Each node in the stack contains data and link to the next node.
TOP pointer points to last node inserted in the stack.
Step 2: The operations on the stack are
a)PUSH data into the stack
b)POP data out of stack
Step 3: PUSH DATA INTO STACK
3a. Enter the data to be inserted into stack.
3b. If TOP is NULL the input data is the first node in stack. the link of the node is NULL.TOP points to that node.
3c. If TOP is NOT NULL the link of TOP points to the new node. TOP points to that node.
Step 4: POP DATA FROM STACK
4a.If TOP is NULL
4b.If TOP is NOT NULL the link of TOP is the current TOP. the pervious TOP is popped from stack.
Step 5. The stack represented by linked list is traversed to display its content.
Implementation of the above program:
# include<stdio.h>
# include<conio.h>
struct node
{
int info;
struct node *link;
}
*top=NULL;
main()
{
int choice;
while(1)
{
printf("1.Push\n");
printf("2.Pop\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("Enter your choice : ") ;
scanf("%d", &choice);
switch(choice)
{
case 1: push(); break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(1);
default :
printf("Wrong choice\n");
}/*End of switch */
}/*End of while */
}/*End of main() */
push()
{
struct node *tmp;
int pushed_item;
tmp = (struct node *)malloc(sizeof(struct node));
printf("Input the new value to be pushed on the stack : ");
scanf("%d",&pushed_item);
tmp->info=pushed_item;
tmp->link=top;
top=tmp;
}/*End of push()*/
pop()
{
struct node *tmp;
if(top == NULL)
printf("Stack is empty\n");
else
{
tmp=top;
printf("Popped item is %d\n",tmp->info);
top=top->link;
free(tmp);
}
}/*End of pop()*/
display()
{
struct node *ptr;
ptr=top;
if(top==NULL)
printf("Stack is empty\n");
else
{
printf("Stack elements :\n");
while(ptr!= NULL)
{
printf("%d\n",ptr->info);
ptr = ptr->link;
}/*End of while */
}/*End of else*/
}/*End of display()*/
Output:
1. Push
2. POP
3. Display
4. Quit
Enter the choice: 1
Input the new value to be pushed on the stack :. 10
1.Push
2. POP
3.Display
4.Quit
Enter the choice: 1
Input the new value to be pushed on the stack : 20
1.Push
2. POP
3.Display
4.Quit
Enter the choice: 1
Input the new value to be pushed on the stack : 30
1.Push
2. POP
3.Display
4.Quit
Enter the choice: 1
Input the new value to be pushed on the stack : 40
1.Push
2. POP
3.Display
4.Quit
Enter the choice: 3
Elements in the stack:
40
30
20
10
1.Push
2. POP
3.Display
4.Quit
Enter the choice: 2
40 is popped from the stack
1.Push
2. POP
3.Display
4.Quit
Enter the choice: 4
Thanks
Mukesh Rajput
Post A Comment:
0 comments: