Python - Single Linked List

 Python - Single Linked List



class Node:

    """Represents a single node in the linked list."""

    def __init__(self, data):

        self.data = data

        self.next = None # Pointer to the next node, initially None


class LinkedList:

    """Manages the linked list operations."""

    def __init__(self):

        self.head = None # The head points to the first node, initially None for an empty list


    def append(self, data):

        """Adds a new node to the end of the linked list."""

        new_node = Node(data)

        if self.head is None:

            self.head = new_node

            return

        

        last = self.head

        while last.next:

            last = last.next

        last.next = new_node


    def traverse_and_print(self):

        """Traverses the list from head to end and prints all data."""

        current_node = self.head

        while current_node:

            print(current_node.data, end=" -> ")

            current_node = current_node.next

        print("None")


# --- Example Usage ---

llist = LinkedList()


# Append elements to the list

llist.append(3)

llist.append(5)

llist.append(13)

llist.append(2)


# Display the linked list

print("Created linked list:")

llist.traverse_and_print()






Comments