Print the list from tail to head 5

Source: Internet
Author: User

Use stack, reverse can be solved by stack

??

Press the data one by one into the stack first

??

And then another one pops up

??

Another way is to use recursion, recursion is actually similar to the stack

??

Method One:

??

Package printListReversed5;

??

Import Java.util.Stack;

??

public class PrintListReversed5 {

static void Printlistreversed (ListNode head) {

if (head! = null) {

stack<listnode> stack = new stack<> ();

while (head! = null) {

Stack.push (head);

head = Head.nextnode;

}

while (!stack.isempty ()) {

System.out.println (Stack.pop (). data);

}

}

}

??

public static void Main (string[] args) {

TODO auto-generated Method Stub

ListNode Headnode = new ListNode ();

Headnode.data = 1;

Headnode.nextnode = null;

ListNode L1 = new ListNode ();

L1.data = 2;

ListNode L2 = new ListNode ();

L2.data = 3;

Headnode.nextnode = L1;

L1.nextnode = L2;

L2.nextnode = null;

Printlistreversed (Headnode);

}

??

}

??

Class ListNode {

int data;

ListNode NextNode;

}

??

Method Two:

??

private static void printlistreversed (ListNode headnode) {

if (headnode.nextnode!=null) {

Printlistreversed (Headnode.nextnode);

}

System.out.println (Headnode.data);

}

? ?

Print the list from tail to head 5

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.