Data Structures & AlgorithmsHardGATE CS · DSA
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([36, 26, 4, 7, 22, 45, 41, 34]))))- A. [26, 36, 7, 4, 45, 22, 34, 41]
- B. [26, 36, 7, 4, 45, 22, 41, 34]
- C. [36, 26, 7, 4, 45, 22, 34, 41]
- D. [26, 4, 7, 22, 45, 41, 34, 36]
Correct answer: A. [26, 36, 7, 4, 45, 22, 34, 41]
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: [26, 36, 7, 4, 45, 22, 34, 41].
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
- How many pairs (i < j) of [2, 15, 17, 10, 24, 2, 10, 2, 4, 9] have a[i] + a[j] divisible by 4? (Count remainders mod 4 and pair r with 4 −…
- A 2-D array A[0..11][0..29] of 2-byte elements is stored in column-major order starting at address 2000. What is the address of A[9][6]?
- For each day, a monotonic stack finds how many days you must wait for a strictly warmer temperature (0 if never). What is printed? python…
- Longest run of consecutive integers (in any order) using a hash set and starting only from numbers whose predecessor is absent. What is…
- Quickselect returns the k-th smallest element of an unsorted array in expected O(n) time. For [29, 18, 10, 32, 39, 19, 36, 13] and k = 4…
- A peak is an element larger than its neighbours (array ends count as −∞). Binary search runs on [43, 46, 49, 14, 48, 18, 24, 47, 28]…