remove a node from the beginning of a linked list in python

To remove a node from the beginning of a linked list in Python, we need to follow these steps:

  1. Check if the linked list is empty or not. If the linked list is empty, then there is nothing to remove.

  2. If the linked list is not empty, then we need to remove the first node of the linked list.

  3. Before removing the first node, we need to assign the head node's next pointer to the second node of the linked list.

  4. After that, we can safely remove the first node of the linked list.

Here's the Python code to remove a node from the beginning of a linked list:

main.py
class Node:
    def __init__(self, data=None, next_node=None):
        self.data = data
        self.next_node = next_node

class LinkedList:
    def __init__(self):
        self.head = None
    
    def remove_first_node(self):
        if self.head is None:
            print("Linked list is empty")
            return
        self.head = self.head.next_node
        print("First node removed")
        
    def print_linked_list(self):
        if self.head is None:
            print("Linked list is empty")
            return
        temp = self.head
        while temp is not None:
            print(temp.data, end=" ")
            temp = temp.next_node

# Example usage
linked_list = LinkedList()
linked_list.head = Node(1)
second_node = Node(2)
third_node = Node(3)
linked_list.head.next_node = second_node
second_node.next_node = third_node

linked_list.print_linked_list()
# Output: 1 2 3

linked_list.remove_first_node()
# Output: First node removed

linked_list.print_linked_list()
# Output: 2 3
1006 chars
42 lines

In the above code, we define a Node class to represent a node in the linked list. And, we define a LinkedList class with two methods: remove_first_node() to remove the first node from the linked list, and print_linked_list() to print the contents of the linked list. Finally, we create an instance of the LinkedList class, add some nodes to it, and perform the removal operation on the first node.

gistlibby LogSnag