Reverse list

3 snippets across 2 stacks — Python, Interview Prep

Also written as list reversal

PYPython

List Slicing

PY · Lists
syntax
items[start:stop:step]
example
nums = [10, 20, 30, 40, 50, 60]
print(nums[1:4])
print(nums[::2])
print(nums[::-1])
nums[1:3] = [200, 300]
print(nums)
output
[20, 30, 40]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]
[10, 200, 300, 40, 50, 60]

Note Slice assignment can replace a range of elements. The replacement does not need to be the same length as the slice being replaced.

Sorting & Reversing

PY · Lists
syntax
list.sort(key=None, reverse=False)
sorted(iterable, key=None, reverse=False)
example
prices = [29.99, 5.50, 12.00, 89.99]
prices.sort()
print(prices)

names = ["Charlie", "alice", "Bob"]
ordered = sorted(names, key=str.lower)
print(ordered)
output
[5.5, 12.0, 29.99, 89.99]
['alice', 'Bob', 'Charlie']

Note .sort() modifies the list in place and returns None. sorted() returns a new list. Use key= for custom ordering logic.

DSAInterview Prep

Reverse a Linked List

DSA · Linked Lists
syntax
Iterative: maintain prev, current, next pointers.
At each step: save next, point current.next to prev, advance both.
example
// JavaScript — Iterative
function reverseList(head) {
  let prev = null, current = head;
  while (current !== null) {
    const next = current.next;
    current.next = prev;
    prev = current;
    current = next;
  }
  return prev;
}

// Recursive
function reverseListRecursive(head) {
  if (!head || !head.next) return head;
  const newHead = reverseListRecursive(head.next);
  head.next.next = head;
  head.next = null;
  return newHead;
}

# Python — Iterative
def reverse_list(head):
    prev, current = None, head
    while current:
        nxt = current.next
        current.next = prev
        prev = current
        current = nxt
    return prev

# Recursive
def reverse_list_recursive(head):
    if not head or not head.next:
        return head
    new_head = reverse_list_recursive(head.next)
    head.next.next = head
    head.next = None
    return new_head
output
1→2→3→4 becomes 4→3→2→1

Note Iterative: O(n) time, O(1) space. Recursive: O(n) time, O(n) stack space. This is the single most common linked list question. Draw the pointer changes on paper. Follow-up: reverse a sublist from position m to n.