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([8, 57, 39, 2, 28, 5, 15, 42]))))- A. [8, 39, 15, 28, 57, 2, 5, 42]
- B. [8, 39, 28, 15]
- C. [8, 39, 28, 15, 57, 5, 2, 42]
- D. [8, 39, 28, 15, 57, 2, 5, 42]
Correct answer: D. [8, 39, 28, 15, 57, 2, 5, 42]
The rearrangement is by position, not by value parity: positions 1, 3, 5, … then 2, 4, 6, …. Output: [8, 39, 28, 15, 57, 2, 5, 42].
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
- What is the length of the longest contiguous substring of ((()((()(()) that is a valid (balanced) parentheses string?
- Reverse a singly linked list in groups of k (a final group shorter than k is left as it is). What is printed? python def revk(h, k): cnt…
- Merge two sorted linked lists by relinking nodes (ties take the node from the first list). What is printed? python def merge(a, b): d = t…
- Print a matrix in spiral order (right, down, left, up, repeat). What is printed? python m = [[90, 11, 62, 33], [40, 71, 82, 13], [10, 81…
- A 2-D array A[0..11][0..29] of 4-byte elements is stored in row-major order starting at address 1000. What is the address of A[5][11]?
- For the sorted array [1, 5, 6, 7, 7, 7, 8, 9, 9, 10, 10, 11] (0-based), what are lowerbound(9) (first index with value ≥ 9) and…