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