Advertisement
shimul07

stack using linked list

Mar 19th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. struct Node {
  4.    int data;
  5.    struct Node *next;
  6. };
  7. struct Node* top = NULL;
  8. void push(int val) {
  9.    struct Node* newnode = (struct Node*) malloc(sizeof(struct Node));
  10.    newnode->data = val;
  11.    newnode->next = top;
  12.    top = newnode;
  13. }
  14. void pop() {
  15.    if(top==NULL)
  16.       cout<<"Stack Underflow"<<endl;
  17.    else {
  18.       cout<<"The popped element is "<< top->data <<endl;
  19.       top = top->next;
  20.    }
  21. }
  22. void display() {
  23.    struct Node* ptr;
  24.    if(top==NULL)
  25.       cout<<"stack is empty";
  26.    else {  
  27.       ptr = top;
  28.       cout<<"Stack elements are: ";
  29.       while (ptr != NULL) {
  30.          cout<< ptr->data <<" ";
  31.          ptr = ptr->next;
  32.       }
  33.    }
  34.    cout<<endl;
  35. }
  36. int main() {
  37.    int ch, val;
  38.    cout<<"1) Push in stack"<<endl;
  39.    cout<<"2) Pop from stack"<<endl;
  40.    cout<<"3) Display stack"<<endl;
  41.    cout<<"4) Exit"<<endl;
  42.    do {
  43.       cout<<"Enter choice: "<<endl;
  44.       cin>>ch;
  45.       switch(ch) {
  46.          case 1: {  
  47.             cout<<"Enter value to be pushed:"<<endl;
  48.             cin>>val;
  49.             push(val);
  50.             break;
  51.          }
  52.          case 2: {
  53.             pop();
  54.             break;
  55.          }
  56.          case 3: {
  57.             display();
  58.             break;
  59.          }
  60.          case 4: {
  61.             cout<<"Exit"<<endl;
  62.             break;
  63.          }
  64.          default: {
  65.             cout<<"Invalid Choice"<<endl;
  66.          }
  67.       }
  68.    }while(ch!=4);
  69.       return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement