Skip to problem
←

Zigzag Linked List

Medium 0 attempts

Modify a nonempty singly linked list so its values follow the pattern:

a0 <= a1 >= a2 <= a3 >= a4 …

The first comparison must be <=, and subsequent comparisons alternate. Equality is allowed. Preserve the number of nodes and every value's occurrence count. Swapping node values is permitted; the task does not require preserving their original positions.

Change the list starting at the original head. The function's return value is ignored. Any final ordering that meets the pattern is accepted, even if it differs from the displayed example.

For [3, 2, 1], [2, 3, 1] is valid. A one-node list already qualifies. Your function receives nodes with val and next properties; examples display their values as arrays.

Function contract

Implement zigZagList(head). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Modify argument 1 in place. The editor compares its final value; the function return value is ignored. Returned list heads are displayed as value arrays; a null head is []. Any result satisfying the statement is accepted.

Example 1

Input
head = [4,3,7,8,6,2,1]
Output
[3,7,4,8,2,6,1]

Example 2

Input
head = [1]
Output
[1]
Constraints
  • 1 <= N <= 10^4
  • Node values are safe JavaScript integers; duplicate values are allowed.

Fix Adjacent Comparisons Greedily

Walk the list from left to right, alternating the required comparison. When a pair violates it, swap the two values; otherwise leave them alone.

This does not break the previous comparison. When fixing current <= next, a swap makes current smaller, preserving the preceding previous >= current. When fixing current >= next, a swap makes current larger, preserving the preceding previous <= current.

After each step, every comparison through that pair is correct. Value swaps preserve the multiset of input values and leave all node links unchanged. Equal values require no swap.

javascript
function zigZagList(head) {
  let curr = head,
    flag = true;
  while (curr && curr.next) {
    if (
      (flag && curr.val > curr.next.val) ||
      (!flag && curr.val < curr.next.val)
    )
      [curr.val, curr.next.val] = [curr.next.val, curr.val];
    curr = curr.next;
    flag = !flag;
  }
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript