O (1) Time complexity reverse stack and sort stack

Source: Internet
Author: User

Both of these operations are recursive implementations, Hanoi thought.

1. Reverse Stack

void Reversestack (stack& stack) {    if (stack. Count = = 0)        return;    Object top = stack. Pop ();    Reversestack (stack);    if (stack. Count = = 0)    {        stack. Push (top);        return;    }    Object TOP2 = stack. Pop ();    Reversestack (stack);                P1    Stack. Push (top);    Reversestack (stack);                 P2    stack. Push (TOP2);        }
Example:
such as stacks
1
2 Object top = stack. Pop (); Post stack becomes 2
3 3
4 4
Reversestack (stack); Post Station becomes
4
3
2
Object TOP2 = stack. Pop ();
3
2
(Note that 1 is the top element of the stack, and 4 is the stack-bottom element)
Then Reversestack (stack);//P1 becomes
2
3
Then stack. Push (top), change to
1
2
3
(This step finds that the stack bottom element 4 is removed)
Here's the
3
2
1
Finally,
4
3
2
1

2, sorting stacks, using the idea of reverse stack to achieve

void Sort (stack& stack) {    if (stack. Count = = 0)        return;    Object top = stack. Pop ();    Sort (stack);    if (stack. Count = = 0)    {        stack. Push (top);        return;    }    Object TOP2 = stack. Pop ();    if ((int) top > (int) top2)    {        stack. Push (top);        Sort (stack);        Stack. Push (TOP2);    }    else    {        stack. Push (TOP2);        Sort (stack);        Stack. Push (top);}    }


O (1) Time complexity reverse stack and sort stack

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.