Rotate a Linked List | Linked List Problem | LeetCode 61
4 years ago Lalit Bhagtani 0
Problem Statement
You have given a singly linked list and an integer k, rotate the linked list to the right by k places.
Example
Input :- head = [5, 4, 10, 15, 1], k = 2 Output :- [15, 1, 5, 4, 10]
Input :- head = [0, 1, 2], k = 4 Output :- [2, 0, 1]
Solution
This problem can be solved in the following steps :-
- Traverse the given linked list, to find out the total number (count) of nodes in the list. If given integer value k is greater than or equal to count, then perform modulus operation on k (k = k % count)
- If the value of k is greater than zero, then create two variables first and second pointing to the head of the linked list.
- Move the second variable to the right by k places.
- Move both first and second variables together, until the second variable reaches last node of the linked list.
- Assign null to first.next, head to second.next.
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.rotateRight(head, 2); ListNode listNode = head; while(listNode != null) { System.out.print(listNode.value + ", "); listNode = listNode.next; } } /* Solution */ public ListNode rotateRight(ListNode head, int k) { if(head != null){ ListNode temp = head; int count = 0; while(temp != null){ temp = temp.next; count++; } if(k>=count){ k = k%count; } if(k > 0){ ListNode first = head; ListNode second = head; while(k>0){ second = second.next; k--; } while(second.next != null){ first = first.next; second = second.next; } temp = first.next; first.next = null; second.next = head; return temp; } } return head; } /* Definition of Linked List Node */ public static class ListNode { int value; ListNode next; public ListNode(int value) { this.value = value; } } }
Result
15, 1, 5, 4, 10,
That’s all for Rotate a Linked List in Java, If you liked it, please share your thoughts in a comments section and share it with others too.