FastPrepRearrange a Linked List from Alternating Ends

Rearrange a Linked List from Alternating Ends

Concentric AI logoConcentric AI● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

Rearrange a singly linked list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln-1 → ….

Reuse the existing nodes and return the head. Do not change node values.

Function

rearrangeList(head: ListNode) → ListNode

Examples

Example 1

head = [1,2,3,4]return = [1,4,2,3]

The alternating order is 1,4,2,3.

Example 2

head = [1,2,3,4,5]return = [1,5,2,4,3]

The middle node remains last.

Example 3

head = []return = []

An empty list stays empty.

Constraints

  • The list contains at most 100000 nodes.
  • Node values fit in a signed 32-bit integer.

More Concentric AI problems

See Concentric AI hiring insights
/** Definition for singly-linked list.
 * class ListNode { int val; ListNode next; }
 */
public ListNode rearrangeList(ListNode head) {
    // write your code here
}
head[1,2,3,4]
expected[1,4,2,3]
Checking account…