You cannot copy content of this page.

Program to implement Stack using Linked List

Program to implement Stack using Linked List



Stacks

Program to implement Stack using Linked List:

/*Implementation of stacks using linked list*/

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#define MAX 10

typedef struct stack
{
int info;
struct stack *next;
}stack;

/*create to allocate memory*/
stack *create()
{stack *temp = (stack *)malloc(sizeof(stack));
if(temp==NULL)
{printf(“nMemory allocation error!”);
exit(1);
}
return temp;
}

/*makenode to initialize new node*/
stack *makenode(int x)
{stack *temp=create();
temp->info=x;
temp->next=NULL;
return temp;
}

/*push to insert an element in list at beginning*/
stack *push(stack *top,int x)
{stack *temp;
stack *ptr=makenode(x);
if(top==NULL)
{top=ptr;
}
else
{ptr->next=top;
top=ptr;
}
}



/*pop to remove top element from stack*/

stack *pop(stack *top)
{stack *temp;
if(top==NULL)
{printf(“nStack Empty! Underflow.”);
return NULL;
}
printf(“nPopped element: %d”,top->info);
temp=top;
top=top->next;
free(temp);
return top;
}

/*displays contents of stack*/
void display(stack *top)
{
stack *temp;
if(top==NULL)
{printf(“nStack empty.”);
return;
}
temp=top;
while(temp!=NULL)
{printf(“%d->”,temp->info);
temp=temp->next;
}
printf(“bb “);
}



void main()
{
int ch,num;
stack *top=NULL;
while(1)
{
clrscr();
printf(“nStack-Menu”);
printf(“nn1. Push”);
printf(“n2. Pop”);
printf(“n3. Display”);
printf(“n4. Exit”);
printf(“nnEnter your choice?”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“nEnter number to push?”);
scanf(“%d”,&num);
top=push(top,num);
break;
case 2:
top=pop(top);
break;
case 3:
display(top);
break;
case 4:
exit(0);
default:
printf(“nInvalid choice!”);
}
getch();
}
}


Comments are closed
x Close

Like Us On Facebook