assignment_07.cpp (2336B)
1 /* Perform Stack operations using Linked List implementation. */ 2 3 #include <iostream> 4 using namespace std; 5 6 struct node 7 { 8 int data; 9 node *next; 10 }; 11 12 class Stack 13 { 14 private: 15 node *top; 16 17 public: 18 Stack() { top = nullptr; } 19 20 bool isEmpty() { return (top == nullptr); } 21 22 void push(int val) 23 { 24 node *newNode = new node; 25 newNode->data = val; 26 newNode->next = top; 27 top = newNode; 28 } 29 30 int pop() 31 { 32 if (isEmpty()) 33 { 34 cout << "Stack Underflow!\n"; 35 return -1; 36 } 37 node *temp = top; 38 int val = temp->data; 39 top = top->next; 40 delete temp; 41 return val; 42 } 43 44 int peek() 45 { 46 if (isEmpty()) 47 { 48 cout << "Stack is empty!\n"; 49 return -1; 50 } 51 return top->data; 52 } 53 54 void display() 55 { 56 if (isEmpty()) 57 { 58 cout << "Stack is empty!\n"; 59 return; 60 } 61 node *temp = top; 62 while (temp != nullptr) 63 { 64 cout << temp->data << " "; 65 temp = temp->next; 66 } 67 cout << endl; 68 } 69 70 ~Stack() 71 { 72 node *temp; 73 while (top != nullptr) 74 { 75 temp = top; 76 top = top->next; 77 delete temp; 78 } 79 } 80 }; 81 82 int main() 83 { 84 Stack s; 85 int choice, val; 86 87 while (true) 88 { 89 cout << "1.push 2.pop 3.peek 4.isEmpty 0.Display -1.Exit\n"; 90 cout << "Enter your choice: "; 91 cin >> choice; 92 93 switch (choice) 94 { 95 case 1: 96 cout << "Enter value: "; 97 cin >> val; 98 s.push(val); 99 break; 100 101 case 2: 102 { 103 int v = s.pop(); 104 if (v != -1) 105 cout << "Popped value: " << v << endl; 106 break; 107 } 108 109 case 3: 110 { 111 int v = s.peek(); 112 if (v != -1) 113 cout << "Top element: " << v << endl; 114 break; 115 } 116 117 case 4: 118 cout << (s.isEmpty() ? "Empty\n" : "Not empty\n"); 119 break; 120 121 case 0: 122 s.display(); 123 break; 124 125 case -1: 126 cout << "Exiting...\n"; 127 return 0; 128 129 default: 130 cout << "Wrong choice.\n"; 131 } 132 } 133 }