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;
        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);
  = n2; = n3; = n4; = n5; = n6;
        System.out.print("Itmes in LinkedList before reverse:");
        System.out.print("Itmes in LinkedList After reverse :");
     public static void printList(ListNode x) {
            if(x != null){
                System.out.print(x.val + "->");
                while ( != null) {
                    System.out.print( + "->");
                    x =;


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