Data Structures

How do you implement a linked list in Python?

Medium
4
Added
A linked list is a linear data structure where each element is a separate object. Each element (or node) of a list consists of two items - the data and a reference to the next node.

Solution Code

Data Structures
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 not self.head:
            self.head = new_node
            return
        last = self.head
        while last.next:
            last = last.next
        last.next = new_node

# Example usage
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
Explanation
This code snippet demonstrates how to implement a linked list in Python.

Guided Hints

Define a Node class
Define a LinkedList class with a head
Implement an append method to add nodes