Title Description
Write a program that sorts the stack in ascending order (that is, the largest element is at the top of the stack), requiring only one additional stack to hold temporary data, but not copying elements into other data structures.
Given a int[] numbers(vector<int> in C + +), where the first element is the top of the stack, return the sorted stack. Note that this is a stack, meaning that you can only access the first element during the sorting process.
Test examples:
[1,2,3,4,5]
return: [5,4,3,2,1]
class twostacks {public:vector<int> twostackssort (vector<int> numbers) { Write code here stack<int> st1; Stack<int> St2; int n = numbers.size (); if (n<=1) return numbers; int temp; for (int i=0;i<n;i++) {temp = numbers[i]; for (; St1.empty () ==false;) {if (Temp<st1.top ()) {St2.push (St1.top ()); St1.pop (); } else {break; }} st1.push (temp); while (St2.empty () ==false) {St1.push (St2.top ()); St2.pop (); }} vector<int> v; while (St1.empty () ==false) {V.push_back (St1.top ()); St1.pop (); } return v; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm title: Double Stack Sort