Write a Function Reverse the nodes of a linked list


The Java code provided demonstrates how to reverse the nodes of a linked list.

  • The code defines a class named Reverse_Nodes with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a LinkedList object named list is created, which represents the linked list. Note that LinkedList is a custom implementation of a linked list, defined in the same code.
  • Nodes with data values 34, 18, 23, 2, and 9 are added to the list using the Node class constructor and setting the next references between the nodes.
  • The code then prints the given linked list using the printList method of LinkedList, which iterates through the linked list and prints the data of each node.
  • Next, the reverse method is called with the head of the linked list as the input, which reverses the nodes of the linked list in place.
  • The reverse method uses three pointers - prev, current, and next - to reverse the next references of the nodes in the linked list.
  • The while loop in the reverse method iterates through the linked list from the head to the end, updating the next references of each node to point to the previous node, effectively reversing the order of the nodes.
  • Finally, the reverse method updates the head of the linked list to the last node, which becomes the new head of the reversed linked list.
  • The code then prints the reversed linked list using the printList method, which iterates through the reversed linked list and prints the data of each node.
  • The output of the program will be the given linked list in its original order, followed by the same linked list reversed.

Source Code

import java.util.*;
class Reverse_Nodes
{	
	public static void main(String[] args)
	{
		LinkedList list = new LinkedList();
		list.head = new Node(34);
		list.head.next = new Node(18);
		list.head.next.next = new Node(23);
		list.head.next.next.next = new Node(2);
		list.head.next.next.next.next = new Node(9);
 
		System.out.println("Given Linked list");
		list.printList(head);
		head = list.reverse(head);
		System.out.println("");
		System.out.println("Reversed Linked list ");
		list.printList(head);
	}
 
	static Node head;
	static class Node {
 
		int data;
		Node next;
 
		Node(int d)
		{
			data = d;
			next = null;
		}
	}
 
	Node reverse(Node node)
	{
		Node prev = null;
		Node current = node;
		Node next = null;
		while (current != null) {
			next = current.next;
			current.next = prev;
			prev = current;
			current = next;
		}
		node = prev;
		return node;
	}
 
	void printList(Node node)
	{
		while (node != null) {
			System.out.print(node.data + " ");
			node = node.next;
		}
	}	
}

Output


Example Programs