Monday, 30 January 2017

Implementing Stack using Linked List

#include <stdio.h>
#include <stdlib.h>
struct node
{
 int data;
 struct node *next;
};
struct node *top=NULL,*c,*p;
push()
{
 int val;
 printf("\nenter a value to insert into stack\n");
 scanf("%d",&val);
 struct node * newnode=malloc(sizeof(struct node));
 newnode->data=val;
 newnode->next = NULL;
 if(top == NULL)
  top = newnode;
 else
 {
  newnode->next=top;
  top=newnode;
 }
}
pop()
{
 if(top == NULL)
 {
  printf("\n Stack is EMPTY..Deletion is not possible");
  return;
 }
 printf("\n Deleted element = %d\n",top->data);
 c=top;
 top=top->next;
 free(c);
}
display()
{
 if(top == NULL)
 {
  printf("stack is empty");
  return;
 }
 else
 {
  for(c=top;c!=NULL;c=c->next)
   printf("%d\t",c->data);
 
 }
}
main()
{
 int opt;
  while(1)
 {
  printf("\nPress 1. Push\t 2. Pop\t3. Display \t4. Exit \n");
scanf("%d",&opt);
switch(opt)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
}
 }

}

1 comment:

  1. good and efficient solution, thanks man
    Refer below link for code in c++, python and java
    http://code2begin.blogspot.com/2016/11/stack-implementation-using-array.html

    ReplyDelete