STACK USING LINKED LIST

                                                STACK USING LINKED LIST


#include <stdio.h>
void push();
void pop();
void display();
struct node
{
 int info;
 struct node *link;
} *top = NULL;
int item;
void main()
{
 int ch;

 do
 {
 printf("\n\n1. Push\n2. Pop\n3. Display\n4. Exit\n");
 printf("\nEnter your choice: ");
 scanf("%d", &ch);
 switch(ch)
 {
 case 1:
 push();
break;
 case 2:
 pop();
break;
 case 3:
 display();
break;
 case 4:
 exit(0);
 default:
 printf("Invalid choice. Please try again.\n");
 }
 } while(1);
 getch();
}
void push()
{
 struct node *ptr;
 printf("\n\nEnter ITEM: ");
 scanf("%d", &item);
 if (top == NULL)
 {
 top = (struct node *)malloc(sizeof(struct node));
 top->info = item;
 top->link = NULL;
 }
 else
 {
 ptr = top;
 top = (struct node *)malloc(sizeof(struct node));
 top->info = item;
 top->link = ptr;
 }
 printf("\nItem inserted: %d\n", item);
}
void pop()
{
 struct node *ptr;
 if (top == NULL)
 printf("\n\nStack is empty\n");
 else
 {
 ptr = top;
 item = top->info;
 top = top->link;
 free(ptr);

 printf("\n\nItem deleted: %d", item);
 }
}
void display()
{
 struct node *ptr;
 if (top == NULL)
 printf("\n\nStack is empty\n");
 else
 {
 ptr = top;

 while(ptr != NULL)
 {
 printf("\n\n%d", ptr->info);
 ptr = ptr->link;
 }
 }
}

OUTPUT


0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More