CCI: Sort a stack

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 | top| empty.

可以提取到数组,然后排序,不过这个显然不是Interviewer想要的答案。只能用栈的操作,那就考虑用一个栈来辅助好了。

#include "stdafx.h"
#include <stack>
#include <iostream>
using namespace std;

stack<int> sortStack(stack<int> s) {
	int val;
	stack<int> sorted;
	while (!s.empty()) {
		val = s.top();
		s.pop();
		while (!sorted.empty() && sorted.top() > val) {
			s.push(sorted.top());
			sorted.pop();
		}
		sorted.push(val);
	}

	return sorted;
}

int _tmain(int argc, _TCHAR* argv[])
{
	stack<int> s;
	s.push(2);
	s.push(1);
	s.push(4);
	s.push(3);

	stack<int> sorted = sortStack(s);

	// Print in reverse order
	cout << "The original stack is: ";
	while (!s.empty()) {
		cout << s.top() << " ";
		s.pop();
	}
	cout << endl;
	cout << "The sorted stack is: ";
	while (!sorted.empty()) {
		cout << sorted.top() << " ";
		sorted.pop();
	}
	cout << endl;

	return 0;
}

时间复杂度O(n^2),还可以。

你可能感兴趣的:(栈)