3.6 Write a program to sort a stack in ascending order (with biggest items on top). You may use additional stacks to hold items, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations:push, pop, peek and isEmpty.
Approach 1: use another stack - O(n^2)
stack<int> sort(stack<int> &s) {
stack<int> r;
while (!s.empty()) {
int x = s.top();
s.pop();
while (!r.empty() && r.top() > x) {
s.push(r.top());
r.pop();
}
r.push(x);
}
return r;
}Approach 2: Recursive - O(n^2)
void insert(stack<int> &s, int x) {
if (s.empty()) {
s.push(x);
} else if (s.top() < x) {
s.push(x);
} else {
int y = s.top();
s.pop();
insert(s, x);
s.push(y);
}
}
void sort(stack<int> &s) {
if (!s.empty()) {
int x = s.top();
s.pop();
sort(s);
insert(s, x);
}
}
本文介绍了一种使用额外栈对堆栈进行升序排序的方法,包括两种实现方式:一种是非递归方法,时间复杂度为O(n^2),另一种是递归方法,同样具有O(n^2)的时间复杂度。方法通过循环从原始堆栈中移除元素,并将这些元素重新插入到新的堆栈中,确保每次插入操作后新堆栈保持升序排列。
426

被折叠的 条评论
为什么被折叠?



