Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Reverse a singly linked list of order IDs.
Problem: Reverse a singly linked list of order IDs.
class Node:
def __init__(self, v, nxt=None):
self.v, self.next = v, nxt
def build(xs):
head = None
for x in reversed(xs):
head = Node(x, head)
return head
def show(h):
out = []
while h:
out.append(h.v); h = h.next
return out
def rev(h):
prev = None
while h:
h.next, prev, h = prev, h, h.next
return prev
print(show(rev(build([1, 2, 3, 4]))))What is printed?- A. [1, 2, 3, 4]
- B. [4]
- C. [4, 3, 2, 1]
- D. [1]
Correct answer: C. [4, 3, 2, 1]
Python evaluates the right side (prev, h, h.next) first, then assigns left to right: h.next = prev, prev = h, h = old h.next. The list is reversed in O(n) time and O(1) space. In other languages you must save next in a temporary before overwriting it.
More Coding Interview Problems questions
- Problem: Return the middle node of a linked list (the second middle when the length is even). python class Node: def init(self, v…
- Problem: Remove the k-th node from the end of a list in one pass. python class Node: def init(self, v, nxt=None): self.v, self.next = v…
- Problem: Merge two sorted linked lists into one sorted list. python class Node: def init(self, v, nxt=None): self.v, self.next = v, nxt…
- Problem: Detect whether a linked list has a cycle and return the value where the cycle starts (None if acyclic). python class Node: def…
- Problem: Reverse the nodes of a linked list k at a time; a final group with fewer than k nodes stays as is. python class Node: def…
- Problem: Add two numbers whose digits are stored in reverse order in linked lists. python class Node: def init(self, v, nxt=None): self.v…