Home Linked List example in Python
Post
Cancel

Linked List example in Python

Introduction

This page describes a python linked list example

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# https://codingnomads.com/how-to-build-linked-lists-in-python

class Node:
    def __init__(self, value=None):
        self.value = value
        self.next = None
    
    def __repr__(self):
        return f"Node({self.value})"


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

    def append(self, value):
        new_node = Node(value)
        if self.head is None:
            self.head = new_node
            self.tail = new_node
        else:
            self.tail.next = new_node
            self.tail = new_node
        self.length += 1

    def prepend(self, value):
        new_node = Node(value)
        if self.head is None:
            self.head = new_node
            self.tail = new_node
        else:
            new_node.next = self.head
            self.head = new_node
        self.length += 1

    def get_node(self, index):
        if index < 0 or index >= self.length:
            return None
        current_node = self.head
        for i in range(index):
            current_node = current_node.next
        return current_node

    def __repr__(self):
        node = self.head
        nodes = []
        while node is not None:
            nodes.append(str(node))
            node = node.next
        nodes.append("None")
        return " -> ".join(nodes)

if __name__ == "__main__":
    # Create a new linked list
    ll = LinkedList()

    # Append a couple of nodes to the linked list
    ll.append(10)
    ll.append(20)
    ll.append(30)

    # Visualize the linked list
    print(ll)  # Node(10) -> Node(20) -> Node(30) -> None

This post is licensed under CC BY 4.0 by the author.

VPN in WSL2

Mathematical Expression Tree in Python