Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

Linked list using python

  1. User

    Linked list using python

  2. Assistant

    A linked list is a linear data structure where elements are stored in nodes, and each node points to the next node in the list. In Python, we can implement a linked list using custom classes for the Node and the LinkedList itself. Here is a basic implementation of a singly linked list in Python:

    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
                return
    
            last_node = self.head
            while last_node.next:
                last_node = last_node.next
    
            last_node.next = new_node
    
        def print_list(self):
            current_node = self.head
            while current_node:
                print(current_node.data, end=" -> ")
                current_node = current_node.next
            print("None")
    
    if __name__ == "__main__":
        linked_list = LinkedList()
        linked_list.append(1)
        linked_list.append(2)
        linked_list.append(3)
        linked_list.append(4)
        linked_list.print_list()  # Output: 1 -> 2 -> 3 -> 4 -> None
    

    In the above code, the Node class represents the individual element in the list, holding the data and the reference to the next node. The LinkedList class manages the overall structure of the list and provides methods to manipulate the list, such as appending elements and printing the list.