Interview Questions: Use One stack to roll back the number in another stack

Source: Internet
Author: User
Question: There are two identical stacks A and B. Stack a Stores numbers from large to small: 1, 2, 3, 4, 5, and the stack top is the minimum number 1, stack B is empty. Instead of using other data structures, we need to reverse the numbers in stack a so that the number of top Stacks is up to 5.

Solution:

  1. This question has a very intuitive idea. First, stack a contains 5 numbers such as 1, 2, 3, 4, and 5, and the top element of the stack is 1. We need to reverse the number to 5, 4, 3, 2, and 1.
  2. First, we need to extract the minimum value of 1 at the top of the stack and store it in the Temporary Variable temp. Then, we need to transfer the remaining four numbers, 2, 3, and 5 to stack B, insert 1 in the temporary variable to stack a, and finally transfer the number in stack B back to stack a. At this time, a book in stack a is sorted, it is the 1 at the bottom of the stack.
  3. Repeat the above ideas. This time, we will take out the minimum value 2 at the top of the stack and store it in the temporary variable. We will transfer the remaining 3, 4, and 5 to stack B, and then insert 2 into stack.

Code instance

View code

# Include <iostream> # include <stdlib. h ># include <stack> using namespace STD; Template <typename T> void reverseorder (stack <t> & S1, stack <t> & S2) {s1.push (5 ); s1.push (4); s1.push (3); s1.push (2); s1.push (1); int sortnum = 0; int oristacksize = s1.size (); While (sortnum <oristacksize) {int temp = s1.top (); s1.pop (); While (s1.size ()-sortnum> 0) {s2.push (s1.top (); s1.pop ();} // store the first element into S1 s1.push (temp); ++ sortnum; whil E (! S2.empty () {s1.push (s2.top (); s2.pop () ;}} cout <"reverse stack output:" <Endl; while (! S1.empty () {cout <s1.top () <Endl; s1.pop () ;}} void main () {stack <int> S1; stack <int> S2; reverseorder (S1, S2); System ("pause ");}

 

 

Related Article

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.