-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompleteStackUsingArray.cpp
More file actions
129 lines (116 loc) · 2.15 KB
/
completeStackUsingArray.cpp
File metadata and controls
129 lines (116 loc) · 2.15 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
126
127
128
129
#include<iostream>
using namespace std;
template <typename T>
class stackUsingArray
{
T *data;
int nextIndex;
int capacity;
public:
//stack of fixed size
// stackUsingArray(int totalElement)
// {
// data=new int[totalElement];
// nextIndex=0;
// capacity=totalElement;
// }
//stack of unlimited size
stackUsingArray()
{
data=new T[4];
nextIndex=0;
capacity=4;
}
//to check size of stack
int getSize()
{
return nextIndex;
}
//to check whether stack is empty or not
bool isEmpty()
{
return nextIndex==0;
}
//to insert elements in stack
// void push(T element)
// {
// if(nextIndex==capacity)
// {
// cout<<"stack full "<<endl;
// return ;
// }
// data[nextIndex]=element;
// nextIndex++;
// }
//to insert element in unlimited size stack
void push(T element)
{
if(nextIndex==capacity)
{
T *newdata=new T[2*capacity];
for(int i=0;i<capacity;i++)
{
newdata[i]=data[i];
}
capacity*=2;
delete [] data;
data=newdata;
}
data[nextIndex]=element;
nextIndex++;
}
//to get topmost element in stack
T top()
{
if(nextIndex==0)
{
cout<<"stack empty "<<endl;
return 0;
}
return data[nextIndex-1];
}
//to pop topmost element in stack
T pop()
{
if(nextIndex==0)
{
cout<<"stack empty "<<endl;
return 0;
}
nextIndex--;
return data[nextIndex];
}
};
int main()
{
// stackUsingArray<int> s(4);
stackUsingArray<int>s;
s.push(10);
s.push(20);
s.push(30);
s.push(40);
s.push(50);
cout<<s.pop()<<endl;
cout<<s.pop()<<endl;
cout<<s.top()<<endl;
cout<<s.getSize()<<endl;
cout<<s.isEmpty()<<endl;
cout<<endl;
stackUsingArray<char>s1;
s1.push('a');
s1.push('b');
s1.push('c');
s1.push('d');
s1.push('e');
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.top()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.top()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.top()<<endl;
cout<<s1.getSize()<<endl;
cout<<s1.isEmpty()<<endl;
}