Sunday, January 26, 2014

C Program to illustrate Linked List Implementation of Stack

with 0 Comment
C Program to illustrate Linked List Implementation of Stack:

Main Program:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include "c:\tc\bin\23llis.c "
void main()
{
int c,d;
clrscr();
while(1)
{
printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
printf("\nEnter your Choice");
scanf("%d",&c);
switch(c)
{
case 1:printf("Enter the element to be pushed");
scanf("%d",&d);
push(d);
break;
case 2:d=pop();
if(d!=1)
printf("The element popped is %d\n",d);else printf("stack is empty");
break;
case 3:display();break;
case 4:exit(0);break;
getch();
}
}
}

SubProgram: (Saved as '23llis.c')

struct node
{
char data;
struct node *next;
};
typedef struct node stack;
stack *top;
void create()
{
top=malloc(sizeof(stack));
top->next=NULL;
}
void display()
{
stack *t;
if(top->next==NULL)
printf("Stack is empty");
else
{
printf("top= ");
for(t=top->next;t!=NULL;t=t->next)
printf("%d\n",t->data);
}
}
int pop()
{
stack *temp,*t;
if(top->next==NULL)
return -1;
else
{
temp=top->next;
top->next=top->next->next;
t=temp;
free(temp);
return(t->data);
}            }
void push(int d)
{
stack *temp;
temp=malloc(sizeof(temp));
temp->data=d;
temp->next=top->next;
top->next=temp;
}

0 comments:

Post a Comment

Powered by Blogger.

Blog Archive