-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray1.cpp
90 lines (71 loc) · 2.07 KB
/
array1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#define MAX_SIZE 100 // define maximum size of stack
using namespace std;
class Stack {
private:
int top; // index of the top element in stack
int arr[100]; // array to store elements of stack
public:
Stack() {
top = -1;
} // constructor to initialize stack
bool is_empty() {
return top == -1;
} // check if stack is empty
void push(int x) {
if (top == MAX_SIZE - 1) { // check if stack is full
cout << "Error: Stack overflow\n";
return;
}
arr[++top] = x; // insert element and update top index
}
int pop() {
if (is_empty()) { // check if stack is empty
cout << "Error: Stack underflow\n";
return -1;
}
return arr[top--]; // return top element and update top index
}
int peek() {
if (is_empty()) { // check if stack is empty
cout << "Error: Stack empty\n";
return -1;
}
return arr[top]; // return top element without removing it
}
int size() { return top + 1; } // return number of elements in stack
};
void prints (Stack s){
if (s.is_empty()){
return;
}
int x = s.peek();
s.pop();
prints(s);
cout << x << " ";
s.push(x);
}
int main() {
//int num;
//cin >> num;
Stack s;
s.push(1);
s.push(2);
s.push(3);
cout << "The stack: ";
prints(s);
cout << endl;
cout << "Size of stack: " << s.size() << endl;
cout << "Top element: " << s.peek() << endl;
s.pop();
cout << "after popping : ";
prints(s);
cout << endl;
cout << "Top element after popping : " << s.peek() << endl;
s.push(4);
cout << "after pushing : ";
prints(s);
cout << endl;
cout << "Top element after pushing: " << s.peek() << endl;
return 0;
}