Data Structures & AlgorithmsHardGATE CS · DSA
Rotate a linked list to the RIGHT by k places (k may exceed the length). What is printed?
Rotate a linked list to the RIGHT by k places (k may exceed the length). What is printed?
def rotate(h, k):
n, t = 1, h
while t.nx: t = t.nx; n += 1
k %= n
if k == 0: return h
t.nx = h
for _ in range(n - k): t = t.nx
h, t.nx = t.nx, None
return h
print(vals(rotate(build([1, 2, 3, 4, 5, 6]), 8)))- A. [6, 1, 2, 3, 4, 5]
- B. [3, 4, 5, 6, 1, 2]
- C. [5, 6, 1, 3, 2, 4]
- D. [5, 6, 1, 2, 3, 4]
Correct answer: D. [5, 6, 1, 2, 3, 4]
Only k mod n rotations matter. The list is made circular and cut after n − (k mod n) steps from the tail. Output: [5, 6, 1, 2, 3, 4].
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
- Exponential search: double the bound i (1, 2, 4, …) until a[i] ≥ key or i passes the end, then binary-search the last range. How many…
- For an n × n matrix whose rows and columns are both sorted ascending, what is the time of the staircase search for a key?
- Swap every two adjacent nodes of a linked list by relinking (not by swapping values). What is printed? python def swappairs(h): d = p =…
- 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…