Data Structures & AlgorithmsModerateGATE CS · DSA

Two ways of finding the middle of a linked list with slow/fast pointers. What is printed?

Two ways of finding the middle of a linked list with slow/fast pointers. What is printed?
h = build([25, 47, 35, 52, 83, 28, 17, 95])
s = f = h
while f and f.nx: s, f = s.nx, f.nx.nx
s2 = f2 = h
while f2.nx and f2.nx.nx: s2, f2 = s2.nx, f2.nx.nx
print(s.v, s2.v)
  1. A. 83 52
  2. B. 83 51
  3. C. 83 53
  4. D. 52 83

Correct answer: A. 83 52

For an even length, the first loop stops on the SECOND middle and the second loop on the FIRST middle; for an odd length both find the same node. Output: 83 52.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic