您的位置:首页 > 其它

Cracking The Coding Interview 3.6

2014-04-11 09:57 288 查看
//	Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write this program: push | pop | peek | isEmpty.
//
//   使用一个临时stack
#include <iostream>
#include <stack>
using namespace std;
class myStack
{
public:
stack<int>s;
public:
myStack(){}

void sort()
{
stack<int>buffer;
while(!s.empty())
{
if (buffer.empty())
{
buffer.push(s.top());
s.pop();
}
else
{
int t = s.top();
s.pop();
while(!buffer.empty() && t > buffer.top())/***注意&&左右判别式的先后***/
{
s.push(buffer.top());
buffer.pop();
}
buffer.push(t);
}
}
while(!buffer.empty())
{
s.push(buffer.top());
buffer.pop();
}
}
};

int main()
{
myStack st;
for (int i =0; i<10; i++)
{
st.s.push(i*((i%2==0)?1:-1));
}
st.sort();
cout<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: