Sunday, September 13, 2015

Java Function Code to create Reverse Linked List of Singly Linked List (In memory pointer changes)

Here is a sample java Function Code to create Reverse Linked List of Singly Linked List (In memory pointer changes). Approach
  • 1) Maintain a previous node pointer
  • 2) maintain a current node pointer
  • 3) store current-> next in temporary variable
  • 4) replace the current node-> next to previous pointer
  • 5) do step 3 and 4 till you reach current node is your end node
  • 6) at the end update the head->next to null as the old linked list head will be your end node now
  • 7) return previous node as this will be the head of your new linked list.
You can see the image below - before and after structure of linked list: java Function Code to create Reverse Linked List
package com.sample.linkedlist;

public class ReverseLinkedList {

 static class Node {
  int data;
  Node next;

  public Node(int data) { = data;

  public String toString() {
   return "Node[data=" + data + "]";


 public static Node reverse(Node head) {

  if (head == null)
   return null;

  Node currentNode =;
  Node previousNode = head;
  while (currentNode != null) {
   System.out.println("previous:" + previousNode +" current:"+currentNode);
   Node tempCurrent =; = previousNode;
   previousNode = currentNode;

   /* move to next node */
   currentNode = tempCurrent;
  } = null;

  return previousNode;

 static void print(Node head) {
  while (head != null) {
   System.out.print(head + " ");
   head =;


 public static void main(String[] args) {
  Node head = new Node(1); = new Node(2); = new Node(3); Node(4);
  /*print actual linked list*/

  Node newHead = reverse(head);

  /*print reversed linked list*/

Node[data=1] Node[data=2] Node[data=3] Node[data=4] 
previous:Node[data=1] current:Node[data=2]
previous:Node[data=2] current:Node[data=3]
previous:Node[data=3] current:Node[data=4]
Node[data=4] Node[data=3] Node[data=2] Node[data=1] 

Please share/ask more data structure problems with us. We will try to solve your problem in coming posts. Also share this post with your friends/classmates.

No comments:

Post a Comment