Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Reverse the nodes of a singly linked list from position m to n (1-based) in one pass.

Problem: Reverse the nodes of a singly linked list from position m to n (1-based) in one pass.
class N:
    def __init__(s, v, nx=None): s.v, s.nx = v, nx
def rev_between(head, m, n):
    dummy = N(0, head); pre = dummy
    for _ in range(m - 1): pre = pre.nx
    cur = pre.nx
    for _ in range(n - m):
        t = cur.nx
        cur.nx = t.nx; t.nx = pre.nx; pre.nx = t
    return dummy.nx
h = None
for v in range(7, 0, -1): h = N(v, h)
h = rev_between(h, 2, 5); out = []
while h: out.append(h.v); h = h.nx
print(*out)
What is printed?
  1. A. 1 5 4 3 2 7 6
  2. B. 1 5 4 3 2 6 7
  3. C. 1 2 5 4 3 6 7
  4. D. 5 4 3 2 1 6 7

Correct answer: B. 1 5 4 3 2 6 7

The head-insertion loop moves each next node to just after pre, so positions 2–5 become 5 4 3 2 while 1, 6 and 7 stay in place. A dummy node makes m = 1 work without a special case.

More Coding Interview Problems questions

Exams that ask this topic