700045. Rearrange a linked list
Medium
Rearrange a Linked List
Slug: rearrange-a-linked-list
Difficulty: Medium
Id: 700045
Topic Tags: Linked List, Data Structures
Company Tags: Amazon, Microsoft
Summary
Given a linked list and an integer k, we need to reorder the nodes in the link list such that all nodes with indices divisible by k are moved to the beginning of the linked list followed by all nodes with indices not divisible by k. The problem is similar to the "Rotate Linked List" problem where we need to rotate the linked list by a certain number of steps.
Detailed Explanation
The algorithm for this problem involves two main steps:
- First, calculate the length of the linked list and the new position of each node.
- Second, rearrange the nodes in the linked list based on their indices.
Here is a step-by-step breakdown:
- Calculate the length of the linked list (n).
- Initialize three pointers: prev, curr, next.
- Traverse the linked list starting from the head and keep track of the number of steps taken (i).
- If i is divisible by k, set the prev pointer to the current node and continue with the next step.
- Otherwise, increment the length counter for nodes not divisible by k.
- Repeat steps 3-5 until the end of the linked list.
- Initialize a new head and traverse the linked list again, this time based on the calculated positions.
- If prev is null, set the new head to the current node and continue with the next step.
- Otherwise, increment the length counter for nodes not divisible by k.
- Repeat steps 3-5 until the end of the linked list.
The time complexity of this algorithm is O(n) where n is the number of nodes in the linked list. The space complexity is O(1) as we only use a constant amount of space to store the pointers and indices.
Optimized Solutions
Java
public class Solution {
public void reorderList(ListNode head, int k) {
int n = 0;
ListNode curr = head;
while (curr != null) {
n++;
curr = curr.next;
}
int pos = 0;
ListNode prev = null;
ListNode curr1 = head;
while (pos < n) {
if (pos % k == 0) {
prev = curr1;
} else {
curr1 = curr1.next;
}
pos++;
}
ListNode newHead = null;
ListNode curr2 = head;
int count = 0;
while (curr2 != null) {
if (count % k == 0 || count >= n) {
newHead = curr2;
} else {
if (newHead == null) {
newHead = curr2;
} else {
ListNode temp = newHead;
while (temp.next != null) {
temp = temp.next;
}
temp.next = curr2;
}
}
curr2 = curr2.next;
count++;
}
}
}