C Program to implement a Stack using a Linked List...

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

struct node
{
    int data;
    struct node* next;
};

struct stack
{
    struct node* head,* top;
};

int flag;

void push(struct stack *p,int x);
int pop(struct stack *p);
int peep(struct stack s);
void display(struct stack s);


void main()
{
  struct stack a;
  printf("Empty Stack is created..");
  a.head=NULL;
  a.top=NULL;
  printf("\nChoice: 1)Insertion 2)Deletion 3)Topmost Element 4)Display 5)Exit");
  int ch,breakcondition=0;
  while(1){
  printf("\nEnter your choice..");
  scanf("%d",&ch);
  switch(ch)
  {
   case 1:{int temp;
          printf("\nEnter the element to be inserted..");
          scanf("%d",&temp);
          push(&a,temp);
          display(a);
          break;
          }
   case 2:{
          int temp;
          flag=0;
          temp=pop(&a);
          if(flag==0)
            printf("\nThe element which is deleted is ..%d",temp);
          display(a);
          break;
          }
   case 3:{
           int temp;
          flag=0;
          temp=peep(a);
          if(flag==0)
            printf("\nThe Topmost element of the stack is ..%d",temp);
          break;
         }
   case 4:{
          display(a);
          break;
          }
   case 5:{
          breakcondition=1;
          break;
          }
   default:printf("\nPlease enter a valid choice..");
 }
 if(breakcondition==1)
  break;
}
}

void push(struct stack *p,int x)
{
    struct node* newnode=(struct node*)malloc(sizeof(struct node));
    newnode->data=x;
    if(p->head==NULL){
        p->head=newnode;
        newnode->next=NULL;
        p->top=p->head;
        return;
    }
    newnode->next=p->head;
    p->head=newnode;
    p->top=p->head;
}

int pop(struct stack *p)
{
    int ans;
    if(p->head==NULL){
        printf("\nThe list is empty..");
        flag=1;
        return ans;
    }
    struct node* trav=p->head;
    ans=trav->data;
    p->head=p->head->next;
    p->top=p->head;
    free(trav);
    return ans;
}
int peep(struct stack s)
{
    int ans;
    if(s.head==NULL){
        printf("\nThe list is empty..");
        flag=1;
        return ans;
    }
    ans=s.top->data;
    return ans;
}


void display(struct stack p)
{
    if(p.head==NULL)  // Corner Case to handle if the list is empty...
    {
        printf("\nThe list is Empty..");
        return;
    }
    printf("\nThe list is..");
    while(p.head!=NULL)  // Traversing the entire list...
    {
        printf("%d ",p.head->data);
        p.head=p.head->next;
    }
}

No comments:

Post a Comment