careercup-Stack and queue 3.6

Source: Internet
Author: User

3.6 Write the program, sort the stack in ascending order (that is, the largest element is at the top of the stack). You can use up to one additional stack to hold temporary data, but you must not copy elements into other data structures (such as arrays). The stack supports the following operations: Push, pop, Peek, and IsEmpty.

Answer

Use an additional stack to simulate the insertion sort. The data in the original stack is compared to the stack top element in the stack, and if the additional stack is empty, the data is pushed directly to the stack. Otherwise, if the stack top element of the additional stack is smaller than the element popped from the original stack, the stack top element of the additional stack is pressed into the original stack. Keep looking like this until the additional stack is empty or the top of the stack element is already greater than the element, the element is pressed into the additional stack.

C + + Implementation code:

#include <iostream>#include<stack>using namespacestd;voidStacksort (stack<int> &St) {Stack<int>T;  while(!St.empty ()) {        intData=St.top ();        St.pop ();  while(!t.empty () &&t.top () <data)            {St.push (T.top ());        T.pop ();    } t.push (data); }     while(!T.empty ())        {St.push (T.top ());    T.pop (); }}intMain () {stack<int>St; intarr[Ten]={2,4,6,1,3,5,7,8,9,0};  for(intI=0;i<Ten; i++) St.push (Arr[i]);    Stacksort (ST);  while(!St.empty ()) {cout<<st.top () <<" ";    St.pop (); } cout<<Endl;}

careercup-Stack and queue 3.6

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.