search

Home  >  Q&A  >  body text

数据结构和算法 - 关于c++栈结构算法题

英文原题:write a program to combine two stacks by placing all elements of the second stack on top of those in the first. The relative ordering of elements from the second stack is unchanged. Following the combine, the second stack is empty. (Hint: you can use push and pop methods of those stacks directly)

意思是:栈1存有 1,2,3,4,5;栈2存有6,7,8,9,10;如何让栈2中的原有数据保持顺序不变而放入栈1中;实现效果是:栈1存有1,2,3,4,5,6,7,8,9,10;栈2为空;

能贴上c++代码最好

PHP中文网PHP中文网2806 days ago702

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 13:02:51

    The answer on the first floor is too troublesome. Just use a temporary stack. The process is:

    1. Create temporary stackt

    2. pops the elements in 栈2 into t in sequence. At this time, the content of t is 10,9,8,7,6

    3. Pop the elements in t into 栈1 in sequence. 栈1The order at this time is exactly from 1 to 10

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:02:51

    Suppose the numbers in stack 1 are sorted from the top of the stack to the bottom of the stack 12345, and the numbers in stack 2 are sorted according to 5678910. Now create a new stack 3, and pop the data in stack 1 to stack 3 in sequence. At this time, the data in stack 3 from the top to the bottom of the stack is 54321, and stack 1 is empty at this time. Create a new stack 4, and push the data in stack 2 to stack 4 one by one. After the push operation, the data in stack 4 is now 109876 from the top of the stack to the bottom of the stack. Then push stack 4 into stack 1. After pushing into stack 1, the data in stack 1 from top to bottom is 678910. Similarly, push stack 3 into stack 1. Then after pushing into stack 1, the data in stack 1 from top to bottom is 678910. is 1234567891.
    Now, the status of the four stacks is that stack 2 is empty, stack 3 is empty (transition stack), stack 4 is empty (transition stack), and stack 1 is 12345678910.

    reply
    0
  • Cancelreply