-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_array.cpp
More file actions
125 lines (107 loc) · 1.95 KB
/
stack_array.cpp
File metadata and controls
125 lines (107 loc) · 1.95 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include<iostream>
using namespace std;
template<typename T>
class Stack{
private:
T *stackArray;
int index;
int capacity;
void changeSize(){
T *newstackArray=new T[capacity*2];
for(int i=0;i<capacity;i++){
newstackArray[i]=stackArray[i];
}
capacity*=2;
delete[]stackArray;
stackArray=newstackArray;
}
public:
Stack(){
capacity=5;
stackArray=new T[capacity];
index=0;
}
Stack(int totalSize){
capacity=totalSize;
stackArray=new int[capacity];
index=0;
}
void push(T element){
if(index==capacity){
changeSize();
}
stackArray[index]=element;
index++;
}
int size(){
return index;
}
bool isEmpty(){
if(size()==0){
return true;
}
else{
return false;
}
}
T pop(){
if(isEmpty()){
cout<<"Empty stack"<<endl;
return 0;
}
else{
int temp=stackArray[index-1];
index=index-1;
return temp;
}
}
T top(){
if(isEmpty()){
cout<<"Empty stack"<<endl;
return 0;
}
else{
return stackArray[index-1];
}
}
};
void reverseStack(Stack<int>s,Stack<int>helper){
if(s.isEmpty() || s.size()==1){
return;
}
int temp=s.top();
s.pop();
reverseStack(s,helper);
while(!s.isEmpty()){
helper.push(s.pop());
}
s.push(temp);
while(!helper.isEmpty()){
s.push(helper.pop());
}
}
void printStack(Stack<int>s){
Stack<int>temp;
while(!s.isEmpty()){
cout<<s.top()<<endl;
temp.push(s.pop());
}
while(!temp.isEmpty()){
s.push(temp.pop());
}
}
int main(){
Stack<int> s1;
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
s1.push(5);
s1.push(6);
s1.push(7);
printStack(s1);
cout<<"After reversing"<<endl;
Stack<int>helper;
reverseStack(s1,helper);
printStack(s1);
}