0%

面试题 03.05. 栈排序

面试题 03.05. 栈排序

用一个栈+临时栈

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
class SortedStack {
public:
SortedStack() {

}

void push(int val) {
stack<int> tmp;
while(!s.empty() && s.top() < val)
{
tmp.push(s.top());
s.pop();
}
s.push(val);
while(!tmp.empty())
{
s.push(tmp.top());
tmp.pop();
}
}

void pop() {
if(s.empty())
return;
s.pop();
}

int peek() {
if(s.empty())
return -1;
return s.top();
}

bool isEmpty() {
return s.empty();
}
private:
stack<int> s;
};

/**
* Your SortedStack object will be instantiated and called as such:
* SortedStack* obj = new SortedStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->isEmpty();
*/