Remove Method in a Doubly Linked List

0

Remove Method in a Doubly Linked List

The remove method allows you to delete a node at a specific index in a doubly linked list.
It handles removing nodes from the beginning, the end, or anywhere in the middle of the list.


🧩 Steps to Remove a Node

  1. Check for invalid index:

    • If index < 0 or index ≥ length, return None.

  2. Remove at the ends:

    • If index == 0: Use the pop_first method.

    • If index == length - 1: Use the pop method.

  3. Remove from the middle:

    • Use a temporary variable to locate the node to remove:

      temp = self.get(index)
    • Redirect the prev and next pointers of surrounding nodes:

      temp.next.prev = temp.prev
      temp.prev.next = temp.next
    • Disconnect the node completely:

      temp.next = None
      temp.prev = None
    • Decrement the length by 1.

  4. Return:

    • Return the removed node (temp) so you have access to it if needed.


💻 Code Example

class DoublyLinkedList:
    def remove(self, index):
        if index < 0 or index >= self.length:
            return None
        if index == 0:
            return self.pop_first()
        if index == self.length – 1:
            return self.pop()
        temp = self.get(index)
        temp.next.prev = temp.prev
        temp.prev.next = temp.next
        temp.next = None
        temp.prev = None
        self.length -= 1
        return temp

🧪 Example Run

dll = DoublyLinkedList(0)
dll.append(1)
dll.append(2)
print(dll.print_list()) # Output: 0, 1, 2

removed_node = dll.remove(1) # Remove the node at index 1

print(removed_node.value) # Output: 1
print(dll.print_list()) # Output: 0, 2

Output:

0, 1, 2
1
0, 2

✅ Key Takeaways

Step Description
1 Validate index (0 ≤ index < length)
2 Handle edge cases with pop_first and pop
3 Redirect pointers of prev and next for middle nodes
4 Disconnect removed node to avoid memory leaks
5 Update length property
6 Return the removed node
  • Time Complexity: O(n) for removing a middle node (traversal using get), O(1) for head or tail.

  • Pointer Management: Always update four pointers in the middle to maintain list integrity.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top