Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Return the middle node of a linked list (the second middle when the length is even).

Problem: Return the middle node of a linked list (the second middle when the length is even).
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 middle(h):
    slow = fast = h
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
    return slow.v
print(middle(build([1, 2, 3, 4, 5])), middle(build([1, 2, 3, 4, 5, 6])))
What is printed?
  1. A. 3 3
  2. B. 2 3
  3. C. 3 5
  4. D. 3 4

Correct answer: D. 3 4

fast moves two steps per slow step, so slow is halfway when fast runs out. For 6 nodes fast stops at None after 3 moves, leaving slow on 4 – the second middle. Using 'while fast.next and fast.next.next' would give the first middle (3). O(n), one pass.

More Coding Interview Problems questions

Exams that ask this topic