Recursively flip a stack reverse a stack using recursion

Source: Internet
Author: User

It is clear that the statements before recursive statements run sequentially, while those after recursive statements run in reverse order.


Package recursion; import Java. util. stack; public class reverse_a_stack_using_recursion {/* input Stack: 3 2 1 Output Stack: 1 2 3 */public static void main (string [] ARGs) {stack <integer> S = new stack <integer> (); S. push (1); S. push (2); S. push (3); insertatbottom (S, 4); system. out. println (s); reversestack (s); system. out. println (s);} // Insert the item to the bottom of stack s public static void insertatbottom (stack <integer> S, int item) {If (S. isempty () {// If the stack is empty, s can be directly added. add (item); return;} int TMP = S. pop (); // Save the top element of the stack to TMP, which is converted to the substack problem insertatbottom (S, item) with one fewer element ); // recursively Insert the item into S. push (TMP); // insert TMP to the top of the stack again} // flip stack s public static void reversestack (stack <integer> S) {If (S. isempty () {return;} int TMP = S. pop (); // Save the top element of the stack to TMP, which is converted to the substack issue reversestack (s) with one fewer element ); // flip the remaining sub-stack insertatbottom (S, TMP); // insert TMP to the bottom of the stack }}




Http://www.geeksforgeeks.org/reverse-a-stack-using-recursion/



Recursively flip a stack reverse a stack using recursion

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.