Data Structures & AlgorithmsHardTCS Digital · Infosys SP
Swap every two adjacent nodes of a linked list by relinking (not by swapping values). What is printed?
Swap every two adjacent nodes of a linked list by relinking (not by swapping values). What is printed?
def swap_pairs(h):
d = p = N(0, h)
while p.nx and p.nx.nx:
a, b = p.nx, p.nx.nx
p.nx, a.nx, b.nx = b, b.nx, a
p = a
return d.nx
print(vals(swap_pairs(build([8, 2, 20, 12, 4, 14, 27, 45]))))- A. [2, 8, 12, 20, 14, 4, 27, 45]
- B. [2, 8, 12, 20, 4, 14, 45, 27]
- C. [2, 8, 12, 20, 14, 4, 45, 27]
- D. [2, 20, 12, 4, 14, 27, 45, 8]
Correct answer: C. [2, 8, 12, 20, 14, 4, 45, 27]
Each step relinks p → b → a → (rest) and moves p to a, the node now second in the pair; an odd last node stays in place. Output: [2, 8, 12, 20, 14, 4, 45, 27].
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Partition a linked list around x: all nodes with value < x come first, then the rest, each part keeping its original relative order. What…
- Two ways of finding the middle of a linked list with slow/fast pointers. What is printed? python h = build([25, 47, 35, 52, 83, 28, 17…
- Evaluate the postfix expression 3 5 4 6 1 ÷ − + + (all divisions are exact). What is its value, and what is the maximum number of operands…
- Count palindromic substrings by expanding around all 2n − 1 centres, and also count DISTINCT palindromic substrings. What is printed?…
- Top-down merge sort (split at mid = n // 2, recurse, then merge, stopping comparisons when one side runs out) sorts [33, 53, 13, 42, 11…
- Assertion (A): Removing duplicates from a sorted array can be done in place in O(n) time with two pointers. Reason (R): In a sorted array…