How to Create a Linked List in Python?

Estimated read time 3 min read

A linked list is a data structure that consists of a sequence of nodes, where each node contains data and a reference to the next node in the list. Here’s how you can create a linked list in Python:

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

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            return
        current_node = self.head
        while current_node.next is not None:
            current_node = current_node.next
        current_node.next = new_node

    def prepend(self, data):
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node

    def delete(self, data):
        if self.head is None:
            return
        if self.head.data == data:
            self.head = self.head.next
            return
        current_node = self.head
        while current_node.next is not None:
            if current_node.next.data == data:
                current_node.next = current_node.next.next
                return
            current_node = current_node.next

    def print_list(self):
        current_node = self.head
        while current_node is not None:
            print(current_node.data)
            current_node = current_node.next

In the code above, we define a Node class that represents each node in the linked list. Each Node has a data attribute to store its value, and a next attribute to store a reference to the next node in the list.

We also define a LinkedList class that represents the linked list as a whole. It has a head attribute to store a reference to the first node in the list.

The append method adds a new node to the end of the list, and the prepend method adds a new node to the beginning of the list. The delete method removes a node from the list that contains the specified data.

Finally, the print_list method prints the values of each node in the list, starting from the head and following the next references until the end of the list is reached.

To create a new linked list and add nodes to it, you can use the following code:

linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.prepend(0)
linked_list.print_list()
# Output: 0 1 2 3

This creates a new linked list, adds nodes with the values 1, 2, and 3 to the end of the list, adds a node with the value 0 to the beginning of the list, and then prints the values of each node in the list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply