NoMatchFound

Stack Implementation with Linked Lists

Jan 27th, 2012
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. // Stack implementation using Linked Lists
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. struct node {
  7.     int data;
  8.     struct node *link;
  9. };
  10.  
  11. struct node *top = NULL, *temp;
  12.  
  13. int main() {
  14.     int choice, data;
  15.  
  16.     // infinite loop is used to insert/delete infinite number of nodes
  17.     while(true) {
  18.         cout << "\n1. Push\n2. Pop\n3. Display\n4. Exit\n";
  19.         cout << "\nEnter ur choice: ";
  20.         cin >> choice;
  21.        
  22.         switch(choice) {
  23.             case 1: // push - add an item to the stack
  24.                 temp = new node;
  25.                 //temp = (struct node *)malloc(sizeof(struct node));
  26.                 cout << "\nEnter a node data: ";
  27.                 cin >> data;
  28.                 temp->data = data;
  29.                 temp->link = top;
  30.                 top = temp;
  31.             break;
  32.             case 2: // pop - print an item from the stack ad delete it
  33.                 if(top != NULL) {
  34.                     cout << "\nThe poped element is:  " << top->data;
  35.                     top = top->link;
  36.                 } else {
  37.                     cout << "\nStack Underflow";
  38.                 }
  39.             break;
  40.             case 3: // print all elements of the stack (without deletion)
  41.                 temp = top;
  42.                 if(temp == NULL) {
  43.                     cout << "\nStack is empty\n";
  44.                 }
  45.  
  46.                 while(temp != NULL) {
  47.                     cout << " -> " << temp->data;
  48.                     temp = temp->link;
  49.                 }
  50.             break;
  51.             case 4: // goes out from infinite loop and terminate the execution
  52.                 return 0;
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment