Stack using Linked List

Implementation of Stack using Linked List.

#include<stdlib.h>
#include<stdio.h>
void push(int);
void pop();
void display();
int ele;
struct stack{
  int data;
  struct stack *next;
};
struct stack *top=NULL;
int main(){
  int opt;
  printf("::Stack Operations::\n1. Push\n2. Pop\n3. Display\n4. Exit\n");
  do{
    printf("Enter your option:\n");
    scanf("%d",&opt);
    switch(opt){
      case 1:
        printf("Enter element:\n");
        scanf("%d",&ele);
        push(ele);
        break;
      case 2:
        pop();
        break;
      case 3:
        display();
        break;
      case 4:
        exit(0);
        break;
      default:
        printf("Wrong option.\n");
    }
  }while(opt!=4);
  return 0;
}
void push(int ele){
  struct stack *ptr;
  ptr=(struct stack*)malloc(sizeof(struct stack));
  ptr->data=ele;
  ptr->next=top;
  top=ptr;
}
void pop(){
  struct stack *ptr;
  if(top==NULL){
    printf("Stack underflow.\n");
    return;
  }
  ptr=top;
  top=top->next;
  printf("Popped item is %d.\n",ptr->data);
  free(ptr);
}
void display(){
  struct stack *ptr;
  if(top==NULL){
    printf("Stack empty.\n");
    return;
  }
  ptr=top;
  printf("Stack elements are:\n");
  while(ptr!=NULL){
    printf("%d->",ptr->data);
    ptr=ptr->next;
  }
  printf("NULL\n");
}
::Stack Operations::
1. Push
2. Pop
3. Display
4. Exit
Enter your option:
1
Enter element:
5
Enter your option:
1
Enter element:
10
Enter your option:
1
Enter element:
15
Enter your option:
3
Stack elements are:
15->10->5->NULL
Enter your option:
2
Popped item is 15.
Enter your option:
3
Stack elements are:
10->5->NULL
Enter your option:
4

No comments:

Post a Comment

Total Pageviews