Now that we have implemented a stack data structure, let's explore the various operations that can be performed on a stack. These operations include:
- Push: Adds an element to the top of the stack.
- Pop: Removes the top element from the stack.
- Peek: Retrieves the top element of the stack without removing it.
The push
operation is used to add elements to the stack. When a new element is pushed onto the stack, it becomes the new top element. The pop
operation, on the other hand, removes the top element from the stack. Lastly, the peek
operation allows us to see the top element of the stack without removing it.
Let's take a look at an example implementation of these stack operations in C++:
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4class Stack {
5private:
6 int arr[100];
7 int top;
8
9public:
10 Stack() {
11 top = -1;
12 }
13
14 void push(int element) {
15 if (top >= 99) {
16 cout << "Stack Overflow" << endl;
17 } else {
18 arr[++top] = element;
19 }
20 }
21
22 int pop() {
23 if (top < 0) {
24 cout << "Stack Underflow" << endl;
25 return -1;
26 } else {
27 return arr[top--];
28 }
29 }
30
31 int peek() {
32 if (top < 0) {
33 cout << "Stack is empty" << endl;
34 return -1;
35 } else {
36 return arr[top];
37 }
38 }
39};
40
41int main() {
42 Stack stack;
43
44 // Pushing elements
45 stack.push(1);
46 stack.push(2);
47 stack.push(3);
48
49 // Popping elements
50 cout << stack.pop() << endl; // Output: 3
51 cout << stack.pop() << endl; // Output: 2
52
53 // Peeking element
54 cout << stack.peek() << endl; // Output: 1
55
56 return 0;
57}