Double-stack sorting of "Programmer interview book" and "Programmer interview book"
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/c5d9c7104e094832bd808a234d00b0b5? Rp = 1 & ru =/ta/cracking-the-coding-interview & qru =/ta/cracking-the-coding-interview/question-ranking
Description
Write a program to sort stacks in ascending order (that is, the maximum element is at the top of the stack). You must use only one additional stack to store temporary data, however, elements cannot be copied to other data structures.
Given an int [] numbers (vector in C ++ <int>), the first element is the top of the stack. Please return the sorted stack. Note that this is a stack, which means that you can only access the first element in the sorting process.
Test example:
[1, 2, 3, 4, 5]
Return Value: [5, 4, 3, 2, 1]
Ideas
Because only one auxiliary stack can be used, each time we retrieve the elements in the stack, we need to compare them with the elements in the auxiliary stack, and put all the auxiliary station elements greater than the elements in the removal into the original stack, repeat this operation until a stack is sorted.
class TwoStacks{public:vector<int> twoStacksSort(vector<int> num){// write code herevector<int> ans;int len = num.size();if(len==0)return ans;while(num.size()!=0){int tmp = num.back();num.pop_back();while(ans.size()!=0 && tmp<ans.back()){num.push_back(ans.back());ans.pop_back();}ans.push_back(tmp);}while(ans.size()!=0){num.push_back(ans.back());ans.pop_back();}return num;}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source