-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.cpp
104 lines (88 loc) · 1.6 KB
/
stack.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <iostream>
using namespace std;
class myStack
{
public:
myStack(int size = 10) : top_(0), cap_(size)
{
stack = new int[cap_];
}
~myStack()
{
delete []stack;
stack = nullptr;
}
//入栈,均摊时间复杂度为O(1)
void push(int val)
{
if(top_ == cap_)
{
expand(2 * cap_);
}
stack[top_++] = val;
}
//出栈 O(1)
void pop()
{
if(top_ == 0)
{
throw "stack is empty!";
}
--top_;
}
//返回栈顶元素 O(1)
int top()
{
if(top_ == 0)
{
throw "stack is empty!";
}
return stack[top_ - 1];
}
//判断栈是否为空 O(1)
bool empty() const
{
return top_ == 0;
}
//返回栈中元素的个数 O(1)
int size() const
{
return top_;
}
private:
void expand(int size)
{
int* p = new int[size];
memcpy(p, stack, sizeof(int) * top_);
delete[] stack;
stack = p;
cap_ = size;
}
private:
int* stack;
int top_;
int cap_;
};
int main()
{
int arr[] = {12, 11, 46, 7, 89, 21, 25, 77};
myStack s;
for(auto v : arr)
{
s.push(v);
}
cout << boolalpha << s.empty() << endl;
cout << s.size() << endl;
cout << s.top() << endl;
cout << "==============" << endl;
s.pop();
cout << s.size() << endl;
cout << s.top() << endl;
while(!s.empty())
{
cout << s.top() << endl;
s.pop();
}
cout << endl;
return 0;
}