Double-stack sorting of "Programmer interview book" and "Programmer interview book"

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.