Vulkan

Cracking The Coding Interview 3.6

//	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;
}

posted on 2014-04-11 09:57  Vulkan  阅读(133)  评论(0编辑  收藏  举报

导航