Skip to Content
Course content

448: Solving Linked List Problems

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Linked lists are where a lot of developers first start feeling the "pointer anxiety." Since Python handles memory for us, we don't deal with raw memory addresses, but the logic of manipulating references is exactly the same. The most common mistake I see—and one I made plenty of times early on—is "breaking the chain" before you've secured the next link.

Take a look at this attempt to reverse a singly linked list. It looks logically sound at a glance, but it has a catastrophic flaw.

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

def reverse_list(head):
    prev = None
    current = head
    
    while current:
        # The mistake is right here
        current.next = prev 
        prev = current
        current = current.next 
        
    return prev

The Infinite Loop of Nothingness

If you run this, you'll notice it doesn't actually reverse the list; it just destroys it. The moment we hit current.next = prev, we've severed the connection to the rest of the list. We've told the current node to point backward, which is what we want, but we've forgotten that current.next was our only map to the next node in the sequence.

When the code reaches current = current.next, it isn't moving forward to the next node in the original list. Instead, it's moving back to prev. You've essentially created a tiny loop between two nodes and lost the rest of your data to the garbage collector. This is the "classic" linked list bug: modifying a reference before you've saved the destination.

Saving the Bridge Before Burning It

To fix this, we need a temporary variable to hold the reference to the next node before we overwrite it. I like to think of it as pinning the next node to the table so it doesn't slide away while I'm rearranging the current one.

def reverse_list(head):
    prev = None
    current = head
    
    while current:
        # 1. Save the next node (The Bridge)
        next_node = current.next 
        
        # 2. Reverse the pointer
        current.next = prev 
        
        # 3. Move the window forward
        prev = current
        current = next_node 
        
    return prev

Now, the sequence is safe. We save current.next into next_node, then we flip the pointer. When we finally move current forward, we use that saved reference. It's a simple addition, but it's the difference between a working algorithm and a memory leak.

Dealing with the Edge Case Void

When you're solving these problems, you have to get into the habit of imagining the "empty" or "singular" states. What happens if head is None? What if there's only one node?

  • Empty List: In my fixed code, current starts as None, the while loop never executes, and it returns prev (which is None). That's correct.
  • Single Node: next_node becomes None, current.next becomes None, prev becomes the node, and current becomes None. It returns the single node. Also correct.

I always recommend sketching this out on paper or a whiteboard first. If you can't draw the arrows moving, you're probably going to write a bug that's a nightmare to debug in the console.




📋 Practical Task

Exercise: Deleting the N-th Node from the End of a Singly Linked List

Your task is to implement a function remove_nth_from_end(head, n). Given the head of a linked list and an integer n, remove the n-th node from the end of the list and return the head.

Requirements:

  • The list is guaranteed to be long enough that n is valid.
  • You should try to solve this in one single pass through the list.
  • Hint: Consider using two pointers (a "fast" pointer and a "slow" pointer) spaced n nodes apart. When the fast pointer hits the end, the slow pointer will be exactly where you need it to be.
class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

def remove_nth_from_end(head, n):
    # Your code here
    pass
Rating
0 0

There are no comments for now.

to be the first to leave a comment.