Stack Using Linked List in C

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

typedef struct StackLinked
{
int val;
struct StackLinked *next;
}sl;


sl *push(sl *,int);
int pop(sl **);
int peek(sl *);
int isempty(sl *);

void disp(sl *);


void main()
{
sl *top=NULL;
int ch,v;

while(1)
{
printf("\n\n1) Push\n\n2) Pop\n\n3) Peek\n\n4) Display\n\n5) Exit");
printf("\n Enter your choice :");
scanf("%d",&ch);


switch(ch)
{
case 1:
printf("\n Enter the number you want to push : ");
scanf("%d",&v);
top=push(top,v);

break;

case 2:  if(!isempty(top))
  {
  printf("\n\nYou have popped %d",pop(&top));
  }
  else
  printf("\n\nNothing to pop");
break;
case 3: if(!isempty(top))
  {
  printf("\n\nTop most value is %d",peek(top));
  }
  else
  printf("\nNothing in the stack");
break;

case 4: if(!isempty(top))
  {
  printf("\n\nValues in the stack are: ");
  disp(top);
  }
  else
  printf("\n\nNothing to display");
break;

case 5: exit(0);
default: printf("\n\nWrong choice ");

}


}
}



sl *push(sl *h,int p)
{
sl *temp;
temp=(sl*) malloc(sizeof(sl));
temp->val=p;
temp->next=h;
h=temp;
return h;
}

int pop(sl **h)
{
int v;
v=(*h)->val;
*h=(*h)->next;
return v;

}


int peek(sl *h)
{

return h->val;
}

int isempty(sl *h)
{
if(h==NULL)
return 1;
else
return 0;
}


void disp(sl *h)
{
sl *t;

t=h;
while(t!=NULL)
{
printf("\n|%3d|",t->val);
t=t->next;
}

}

I/O: after copying the code run it. I hope you will be able to understand. If not clear to you feel free to place a comment.

Comments

Popular posts from this blog

JAVA program to add two distance

Print Pattern using C