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:
package com.sample.linkedlist;
public class ReverseLinkedList {
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
@Override
public String toString() {
return "Node[data=" + data + "]";
}
}
public static Node reverse(Node head) {
if (head == null)
return null;
Node currentNode = head.next;
Node previousNode = head;
while (currentNode != null) {
System.out.println("previous:" + previousNode +" current:"+currentNode);
Node tempCurrent = currentNode.next;
currentNode.next = previousNode;
previousNode = currentNode;
/* move to next node */
currentNode = tempCurrent;
}
head.next = null;
return previousNode;
}
static void print(Node head) {
while (head != null) {
System.out.print(head + " ");
head = head.next;
}
System.out.println();
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next=new Node(4);
/*print actual linked list*/
print(head);
Node newHead = reverse(head);
/*print reversed linked list*/
print(newHead);
}
}
Output
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.
Dont SPAM