码迷,mamicode.com
首页 > 编程语言 > 详细

[CTCI] 双栈排序

时间:2015-07-18 15:28:53      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

 双栈排序

题目描述

请编写一个程序,按升序对栈进行排序(即最大元素位于栈顶),要求最多只能使用一个额外的栈存放临时数据,但不得将元素复制到别的数据结构中。

给定一个int[] numbers(C++中为vector<int>),其中第一个元素为栈顶,请返回排序后的栈。请注意这是一个栈,意味着排序过程中你只能访问到第一个元素。

测试样例:
[1,2,3,4,5]
返回:[5,4,3,2,1]


 1 class TwoStacks {
 2 public:
 3     vector<int> twoStacksSort(vector<int> numbers) {
 4         // write code here
 5         stack<int> stk;
 6         int top = 0, tmp;
 7         while (top != numbers.size()) {
 8             tmp = numbers[top++];
 9             while (!stk.empty() && stk.top() > tmp) {
10                 numbers[--top] = stk.top();
11                 stk.pop();
12             }
13             stk.push(tmp);
14         }
15         top = 0;
16         while (!stk.empty()) {
17             numbers[top++] = stk.top();
18             stk.pop();
19         }
20         return numbers;
21     }
22 };

 

[CTCI] 双栈排序

标签:

原文地址:http://www.cnblogs.com/easonliu/p/4656772.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!