您的位置:首页 > 编程语言 > C语言/C++

左神的书——《程序员代码面试指南》之用一个栈实现另一个栈的排序c++实现

2017-01-01 22:56 399 查看
题目:

//用一个栈实现另一个栈的排序

//一个栈中元素的类型为整型,现在想将该栈从顶到底按从大到小的顺序排序,只能申请一个栈,除此之外,可以

// 申请新的变量,但不能申请额外的数据结构。如何完成排序?

#include<iostream>
using namespace std ;
#include <stack>
#include <cassert>

void SortStackByStack(stack<int>& s)
{
assert(!s.empty());

stack<int> helpstack;

while (!s.empty())
{
int value = s.top(); //用一个变量value标记s的栈顶元素。
s.pop();

while (!helpstack.empty() && value > helpstack.top()) //当辅助栈不为空,s的栈顶元素大于辅助栈顶元素,
{ //将辅助栈顶元素压回s中,直到value<辅助栈顶元素,将value压入辅助栈
s.push(helpstack.top());
helpstack.pop();
}

helpstack.push(value); //当辅助栈为空或者s的栈顶元素小于等于辅助栈顶元素,直接将s的栈顶元素压入辅助栈中。

}

while (!helpstack.empty())
{
s.push(helpstack.top());
helpstack.pop();
}
}

int main()
{

stack<int> s1;
s1.push(34);
s1.push(45);
s1.push(23);
s1.push(219);
s1.push(2);
SortStackByStack(s1);
cout << s1.top() <<endl;

cout << "hello..." <<endl;
system("pause");
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: