Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft
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([26, 1, 44, 35, 21, 41, 16, 15]))))- A. [1, 44, 35, 21, 41, 16, 15, 26]
- B. [1, 26, 35, 41, 44, 21, 15, 16]
- C. [1, 26, 35, 44, 41, 21, 16, 15]
- D. [1, 26, 35, 44, 41, 21, 15, 16]
Correct answer: D. [1, 26, 35, 44, 41, 21, 15, 16]
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: [1, 26, 35, 44, 41, 21, 15, 16].
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
- Count distinct values in every window of size k with a frequency map. What is printed? python from collections import Counter a, k = [3…
- A min-stack keeps a second stack of running minimums. What is printed? python st, mn, out = [], [], [] for op in [7, 5, 7, 5, 5, "pop"…
- A hash-map two-sum returns the first index pair (i, j), i < j, found while scanning left to right. What is printed? python def twosum(a…
- A dynamic array doubles its capacity when full, copying all elements. Starting from capacity 1, what is the total number of element copies…
- Evaluate the postfix expression 7 4 1 ÷ 7 + 6 × 2 × + 3 − (all divisions are exact). What is its value, and what is the maximum number of…
- Asteroids move along a line: positive values move right, negative move left; on collision the smaller (by absolute value) explodes, equal…