Back to Dashboard
Rearrange a LinkedList
MediumProblem Statement
Given the head of a Singly LinkedList, write a method to modify the LinkedList such that the nodes from the second half of the LinkedList are inserted alternately to the nodes from the first half in reverse order. So if the LinkedList has nodes 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null, your method should return 1 -> 6 -> 2 -> 5 -> 3 -> 4 -> null.
Your algorithm should use only constant space the input LinkedList should be modified in-place.
Examples
Example 1:
- Input:
head = [1,2,3,4,5,6] - Output:
[1,6,2,5,3,4]
Approach 1 Iterative:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
var slow = head;
var fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
var secondHalf = reverse(slow);
var firstHalf = head;
while (firstHalf != null && secondHalf != null) {
var temp = firstHalf.next;
firstHalf.next = secondHalf;
firstHalf = temp;
temp = secondHalf.next;
secondHalf.next = firstHalf;
secondHalf = temp;
}
if (firstHalf != null) {
firstHalf.next = null;
}
}
private ListNode reverse(ListNode head) {
ListNode prev = null;
while (head != null) {
var next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}