A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to Arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque.
Steps to Solve
Most of these questions follow the same framework
- Identify pattern
- Reverse
- Merge
- Remove nth node
- Partition list
- Rotate list
- Reorder list
- What pointer(s) do I update at each step
- What pointers do I need to track
- Use dummy node?
- Edge cases?
Removing a Node From a Linked List
def remove_node(node):
prev = node.prev
nxt = node.next
prev.next = nxt
nxt.prev = prev
# This just basically skips over our current nodeReversing a Linked List
def reverseList(head):
if not head or head.next is None:
return head
revHead = reverseList(head.next)
head.next.next = head # Making the current head the last node
head.next = None # We are the last node so now point to nothing
return revHeadcurr = head
prev = None
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = next
return prev