Print a single linked list from the end of the head

Source: Internet
Author: User
Tags static class

Use recursion to print the linked list from the end of the head.

Java code

public class listnode{
    ListNode next;
    int Val;
    ListNode (int x) {
    val=x;}

public static void Print_reverse (ListNode head) {
    if (head==null| | Head.next==null) System.out.print (head.val);
    ListNode P=head;
    while (p!=null) {
        if (p.next!=null) {
        print_reverse (p.next);
        }
        System.out.print (p.val+ "\ t");}}}

However, when the list is long, the number of recursive layers is particularly high, which can result in overflow of function calls, so it is better to use the data structure of the stack as a bit more robust.

As shown below:

package binaryTree; import java.util.Stack;
        public class Printlata2first {public static void main (string[] args) {node N1 = new Node (1);
        Node N2 = new node (2);
        node N3 = new node (3);
        Node N4 = new node (4);
        Node N5 = new node (5);
        N1.next = n2;
        N2.next = n3;
        N3.next = N4;
        N4.next = N5;
    Reverseprint (N1);
            public static void Reverseprint (Node head) {stack p = new stack ();//using the stack structure while (head!=null) {
        P.push (head.val);//press into stack head = Head.next;
        } while (!p.empty ()) {System.out.println (p.lastelement ());//print stack top element p.pop ();//Remove
        }} public static class node{int val;
        Node Next;
        Public Node (int val) {this.val = val; }
    }   
}

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.