2014-03-19 03:01

题目:给定一个栈,设计一个算法,在只使用栈操作的情况下将其排序。你可以额外用一个栈。排序完成后,最大元素在栈顶。

解法:我在草稿纸上试了试{1,4,2,3}之类的小例子,大概两三分钟有了思路。既然比较性排序是基于比较和交换的,那么就在两个栈的栈顶进行比较,同时在栈顶进行交换,此处需要O(1)的空间来进行交换。具体实现请看代码,时间复杂度为O(n^2)。

代码:

 1 // 3.6 Try to sort the elements in a stack with the aid of at most one more stack.
 2 #include <cstdio>
 3 #include <stack>
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     void sortStack(stack<int> &s1) {
 9         if (s1.empty()) {
10             return;
11         }
12         // extra O(n) here
13         stack<int> s2;
14         // extra O(1) here
15         int val;
16         
17         while (!s1.empty()) {
18             if (s2.empty() || s1.top() <= s2.top()) {
19                 s2.push(s1.top());
20                 s1.pop();
21             } else {
22                 val = s1.top();
23                 s1.pop();
24                 while (!s2.empty() && s2.top() < val) {
25                     s1.push(s2.top());
26                     s2.pop();
27                 }
28                 s2.push(val);
29             }
30         }
31         while (!s2.empty()) {
32             s1.push(s2.top());
33             s2.pop();
34         }
35     }
36 };
37 
38 int main()
39 {
40     Solution sol;
41     int i, n, val;
42     stack<int> st;
43     
44     while (scanf("%d", &n) == 1 && n > 0) {
45         for (i = 0; i < n; ++i) {
46             scanf("%d", &val);
47             st.push(val);
48         }
49         sol.sortStack(st);
50         
51         printf("%d", st.top());
52         st.pop();
53         while (!st.empty()) {
54             printf(" %d", st.top());
55             st.pop();
56         }
57         printf("\n");
58     }
59     
60     return 0;
61 }

 

 posted on 2014-03-19 03:20  zhuli19901106  阅读(313)  评论(0编辑  收藏  举报