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; }
}
}