Data Structures & AlgorithmsModerateProduct placement · Amazon/Microsoft
Rearrange a linked list so that nodes at odd POSITIONS (1st, 3rd, …) come first, followed by the even-position nodes, keeping relative order. What is printed?
Rearrange a linked list so that nodes at odd POSITIONS (1st, 3rd, …) come first, followed by the even-position nodes, keeping relative order. What is printed?
def odd_even(h):
if not h: return h
odd, even = h, h.nx
ehead = even
while even and even.nx:
odd.nx = even.nx; odd = odd.nx
even.nx = odd.nx; even = even.nx
odd.nx = ehead
return h
print(vals(odd_even(build([54, 20, 7, 17, 27, 38, 22, 49]))))- A. [54, 7, 27, 20, 22, 17, 38, 49]
- B. [54, 7, 27, 22, 20, 17, 38, 49]
- C. [54, 7, 22, 27, 20, 17, 38, 49]
- D. [54, 7, 27, 22]
Correct answer: B. [54, 7, 27, 22, 20, 17, 38, 49]
The rearrangement is by position, not by value parity: positions 1, 3, 5, … then 2, 4, 6, …. Output: [54, 7, 27, 22, 20, 17, 38, 49].
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
- Sort [−4, 3, −3, −5, −4, 5, 2] and, for each i, move two pointers to find the triplet sum closest to -2. What is that closest sum?
- Insertion sort (ascending; shift larger elements right, one key comparison per inner-loop test, the loop stops at the first element ≤ the…
- How many contiguous subarrays of [−2, 0, 5, −1, 4, 3, −1, −2, −3] have sum exactly 4? (Prefix sums with a hash map of prefix-sum…
- For s = "cdbccdddbaddca", what is the length of the longest substring with at most 2 distinct characters, and how many substrings (by…
- For s = "bcadbdaccdddbd", what is the length of the longest substring with at most 2 distinct characters, and how many substrings (by…
- How many contiguous subarrays of [1, 3, 8, 1, 3, 6, 0, 0, 9] have a sum divisible by 3? (Count equal prefix-sum remainders.)