Print a Reversed Linked List
Learn how to print the linked list in reverse order using recursion.
Print a reversed linked list
Given a linked list, access each node in such a way so that the linked list will print in a reversed manner. You may not change the content of the list.
The following illustration explains this concept:
Press + to interact
class LinkedList {// Linked List Nodestatic class Node {int value;Node next;};public static void reverse(Node head) {// Base caseif (head == null) {return;}// Recursive caseelse {reverse(head.next);System.out.print(head.value + " ");}}static Node insertAtHead(Node temp_head, int new_value) {Node new_Node = new Node();new_Node.value = new_value;new_Node.next = (temp_head);(temp_head) = new_Node;return temp_head;}public static void main( String args[] ) {// Empty Linked ListNode head = null;// Linked List = 1->2->3->4->5head = insertAtHead(head, 5);head = insertAtHead(head, 4);head = insertAtHead(head, 3);head = insertAtHead(head, 2);head = insertAtHead(head, 1);// Print the original Linked ListSystem.out.println("Linked List: ");for (Node i = head; i != null; i = i.next) {System.out.print(i.value + " ");}// Print the reversed Linked ListSystem.out.println(" ");System.out.println("Reversed Linked List: ");reverse(head);}}
Understanding the code
The code given above can be broken down into two parts. The recursive method and main ...