Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Regroup a linked list so that all nodes at odd positions (1st, 3rd, …) come first, followed by the even positions, keeping relative order, in O(1) extra space.

Problem: Regroup a linked list so that all nodes at odd positions (1st, 3rd, …) come first, followed by the even positions, keeping relative order, in O(1) extra space.
class Node:
    def __init__(self, v, nxt=None): self.v, self.next = v, nxt
def build(xs):
    head = None
    for x in reversed(xs): head = Node(x, head)
    return head
def show(h):
    out = []
    while h: out.append(h.v); h = h.next
    return out
def odd_even(head):
    if not head: return head
    odd, even = head, head.next
    even_head = even
    while even and even.next:
        odd.next = even.next; odd = odd.next
        even.next = odd.next; even = even.next
    odd.next = even_head
    return head
print(show(odd_even(build([10, 20, 30, 40, 50, 60, 70]))))
What is printed?
  1. A. [20, 40, 60, 10, 30, 50, 70]
  2. B. [10, 30, 50, 20, 40, 60, 70]
  3. C. [10, 30, 50, 70, 60, 40, 20]
  4. D. [10, 30, 50, 70, 20, 40, 60]

Correct answer: D. [10, 30, 50, 70, 20, 40, 60]

Two chains are built by relinking: odd takes every other node starting at the head, even starts at the second node; finally the odd chain's tail points to the saved even head. Positions 1, 3, 5, 7 hold 10, 30, 50, 70. Note it is about positions, not values. O(n) time, O(1) space.

More Coding Interview Problems questions

Exams that ask this topic