Linked List

Write a program to reverse the linked list

Pinterest LinkedIn Tumblr

Write a program to reverse the linked list. The head item should move to tail and tail item should move to head.

Example Given linked list 22->45->67->90->85 and return reverse linked list 85->90->67->45->22.

Algorithm Explanation

Iterate trough the linked list.
Recursively call the reverse list and print the value.
The value printed reverse order when returns to caller.

Source Code

package com.dsacode.DataStructre.linkedlist;
 
public class ReverseLinkedList {
 
    public static void ReversePrint(ListNode head) {
        if(head == null) return;
        ReversePrint(head.next);
        System.out.print( head.val+"->");
    }
     
    public static void main(String args[]){
         
        System.out.println("Insert itmes in LinkedList:9, 43, 34, 11, 78, 55");
        ListNode n1 = new ListNode(9);
        ListNode n2 = new ListNode(43);
        ListNode n3 = new ListNode(34);
        ListNode n4 = new ListNode(11);
        ListNode n5 = new ListNode(78);
        ListNode n6 = new ListNode(55);
  
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        System.out.print("Itmes in LinkedList before reverse:");
        printList(n1);
        System.out.print("Itmes in LinkedList After reverse :");
        ReversePrint(n1);
        System.out.println("NULL");
     }
      
     public static void printList(ListNode x) {
            if(x != null){
                System.out.print(x.val + "->");
                while (x.next != null) {
                    System.out.print(x.next.val + "->");
                    x = x.next;
                }
                System.out.println("NULL");
            }
    }
}

Output

Insert items in LinkedList:9, 43, 34, 11, 78, 55
Items in Linked List before reverse:9->43->34->11->78->55->NULL
Items in Linked List After reverse :55->78->11->34->43->9->NULL

Write A Comment