Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Reverse a singly linked list of order IDs.

Problem: Reverse a singly linked list of order IDs.
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 rev(h):
    prev = None
    while h:
        h.next, prev, h = prev, h, h.next
    return prev
print(show(rev(build([1, 2, 3, 4]))))
What is printed?
  1. A. [1, 2, 3, 4]
  2. B. [4]
  3. C. [4, 3, 2, 1]
  4. D. [1]

Correct answer: C. [4, 3, 2, 1]

Python evaluates the right side (prev, h, h.next) first, then assigns left to right: h.next = prev, prev = h, h = old h.next. The list is reversed in O(n) time and O(1) space. In other languages you must save next in a temporary before overwriting it.

More Coding Interview Problems questions

Exams that ask this topic