Reverse Linked List in Java

 



In this blog we will learn how to do reverse of a linked list in java and understand the logic behind it.


Watch this video to understand how this code works



Code

class Node<T>{

T data;

Node<T> next;

Node(T data){

this.data =data;

}

}

public class Testing{

// function to do the sum of my linked list

public static Node<Integer> reverse(Node<Integer> head){

Node<Integer> pre = null ,curr = head;

while(curr!=null) {

Node<Integer> temp = curr.next;

curr.next = pre;

pre = curr;

curr = temp;

}

return pre;

}

public static void print(Node<Integer> head) {

while(head!=null) {

System.out.print(head.data+" ");

head = head.next;

}

}

public static void main(String[] args) {

//create my linked list

Node<Integer> a = new Node<>(1);

Node<Integer> b = new Node<>(2);

Node<Integer> c = new Node<>(3);

Node<Integer> d = new Node<>(4);

// create the relations

a.next=b;

b.next =c;

c.next=d;

System.out.println("Before Reverse");

print(a);

System.out.println();

System.out.println("After Reverse");

print(reverse(a));

}


}


Previous Blog : 






Post a Comment

0 Comments