Pages

107 while current and while current.next

In linked list problems, both while current and while current.next are common loop conditions, but they serve different purposes depending on what you want to do inside the loop.

Let’s break it down:

while current:

Means: "Keep going as long as the node is not null."

Use it when:
You want to process each node — including the last node.

 Example:


while current:
    print(current.val)
    current = current.next

This loop prints every node’s value, including the last one.

while current.next:

Means: "Keep going as long as the next node exists."

Use it when:
You want to stop at the second-last node — for example, when you need access to the next node or are modifying current.next.

Example:


while current.next:
    current = current.next

This loop stops at the second-to-last node (i.e., it skips the last one) — useful when you want to remove the last node or modify its pointer.

 Use-Case Scenarios and Tips

Common Trick Patterns

1. Skip a Node


while current and current.next:
    if current.next.val == target:
        current.next = current.next.next  # skip it
    else:
        current = current.next
2. Tail Insertion (Traverse to End)

slow = head
fast = head

while fast and fast.next:
    slow = slow.next
    fast = fast.next.next

3. Finding Middle Node (Fast/Slow Pointers)

while current.next:
    current = current.next
current.next = new_node