How to create a linked list in Python?

96 views

How to create a linked list in Python?

How to create a linked list in Python?

solveurit24@gmail.com Changed status to publish February 13, 2025
0

Implement nodes with pointers to the next element.

class Node:
    def __init__(self, data):
        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
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node

    def display(self):
        current = self.head
        while current:
            print(current.data, end=' -> ')
            current = current.next
        print("None")

linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.display()  # Output: 1 -> 2 -> None

solveurit24@gmail.com Changed status to publish February 13, 2025
0