Reverse a Linked List | Linked List Problem
4 years ago Lalit Bhagtani 0
Problem Statement
You have given a singly linked list, write a program to reverse the linked list. Try to do it in-place by changing links between the nodes.
Example
Input :- head = [5, 4, 10, 15, 1] Output :- [1, 15, 10, 4, 5]
Input :- head = [5, 4, 10, 15, 1, 5, 6] Output :- [6, 5, 1, 15, 10, 4, 5]
Solution
This problem can be solved in following steps :-
- Create three variables previous, current, next. Initially assign previous to null, current to head node of linked list and next to second node of linked list.
- Reassign next of current variable node to previous.
- Move all variables by one node, i.e previous = current, current = next and next = next.next
- Go to step 2 until the current variable is not null.
- return previous variable.
Program
public class Main { public static void main(String[] args) { ListNode head = null; ListNode node = new ListNode(5); head = node; node.next = new ListNode(4); node = node.next; node.next = new ListNode(10); node = node.next; node.next = new ListNode(15); node = node.next; node.next = new ListNode(1); Main main = new Main(); head = main.reverseList(head); ListNode listNode = head; while(listNode != null) { System.out.print(listNode.value + ", "); listNode = listNode.next; } } /* Solution */ public ListNode reverseList(ListNode head) { ListNode previous = null; ListNode current = head; ListNode next = null; while(current != null){ next = current.next; current.next = previous; previous = current; current = next; } return previous; } /* Definition of Linked List Node */ public static class ListNode { int value; ListNode next; public ListNode(int value) { this.value = value; } } }
Result
1, 15, 10, 4, 5,
That’s all for Reverse a Linked List in Java, If you liked it, please share your thoughts in a comments section and share it with others too.