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

4 Comments

  1. Witһ havin ѕo much content do you ever run into any issues of
    plagorism or copyright violation? My website hɑs a lot of
    unique content I’ve either written myself or outsourced but it seems a
    lⲟt of it is popping it up ɑll ᧐veг the web without my permission. Do you know any metһods to help stoⲣ
    content from beіng ripped off? I’ɗ genuinely
    appreciate it.

  2. I need to to thank you for this very good read!! I absolutely loved every little bit of it.

    I’ve got you book-marked to check out new things you post…

  3. I have been exploring for a little for any high-quality articles or blog posts on this sort of space .
    Exploring in Yahoo I eventually stumbled upon this website.
    Studying this info So i’m happy to express that
    I have an incredibly good uncanny feeling I found out just what I needed.
    I such a lot undoubtedly will make certain to do not forget this site and provides it
    a look regularly.

Write A Comment