《程序员面试金典》(第六版)习题:仅为记录一下以加强印象,不为商业用途,如有侵权请联系删除。以下源码和解释参考了书中源码以及解释。
算法首先建立一个新的空栈
r
r
r,如果需要排序的栈
s
s
s为空或者只有一个元素则马上返回。否则将要排序的栈
s
s
s的栈顶元素出栈并入栈到新创立的栈
r
r
r。这时新创立的栈
r
r
r因为只有一个元素因此是有序的。接下来不断的从等待排序的栈
s
s
s中拿出栈顶元素并将它入栈到新创立的栈
r
r
r中的适当位置使得新创立的栈
r
r
r继续保持有序状态(栈底的元素较小,栈顶的额元素较大),持续该操作直到栈
s
s
s为空为止,这时栈
r
r
r中已经存储着栈
s
s
s的有序排列,只不过是题目要求的倒序,这时只要将栈
r
r
r中的元素从栈顶开始全部入栈到栈
s
s
s中,栈
s
s
s中就是题目要求的栈的有序排列了(栈底的元素较大,栈顶的额元素较小)。具体操作为从待排序的栈
s
s
s中拿出栈顶元素
m
m
m后不断从新创立的栈
r
r
r中出栈栈顶元素并入栈到待排序的栈
r
r
r中,直到在栈
r
r
r遇到比
m
m
m小或者相等的元素后停止,这时将从栈
s
s
s中拿出栈顶元素入栈到栈
r
r
r中。接下来一直重复该操作,直到栈
s
s
s为空为止。
该算法的时间复杂度为
O
(
n
2
)
O(n^2)
O(n2),空间复杂度为
O
(
n
)
O(n)
O(n),
n
n
n为栈中元素个数。接下来是实现代码和测试程序。图1为测试结果。
void myStackSort(stack<int> & s)
{
stack<int> r = stack<int>();
if (s.empty() || (s.size() == 1))
{
return;
}
r.push(s.top());
s.pop();
while (!s.empty())
{
int temp = s.top();
s.pop();
while (!r.empty() && r.top()>temp)
{
s.push(r.top());
r.pop();
}
r.push(temp);
}
while (!r.empty())
{
s.push(r.top());
r.pop();
}
}
int main()
{
stack<int> testStack;
testStack.push(7);
testStack.push(10);
testStack.push(9);
testStack.push(12);
testStack.push(11);
testStack.push(1);
myStackSort(testStack);
cout<<testStack.top()<<endl;
testStack.pop();
cout << testStack.top() << endl;
testStack.pop();
cout << testStack.top() << endl;
testStack.pop();
cout << testStack.top() << endl;
testStack.pop();
cout << testStack.top() << endl;
testStack.pop();
cout << testStack.top() << endl;
testStack.pop();
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/9a4e19a2f865395a9167fd98fd319626.png)