create a linked list in python

In Python, Linked List can be implemented using the concept of classes and objects. A linked list is a linear data structure in which elements are stored in non-contiguous memory blocks called nodes. Each node contains two fields - data and a reference to the next node. The first node is called the head node, and the last node is called the tail node.

To create a linked list in Python, we first need to create a node class to represent each of the nodes in the list. The node class will have two fields - data and next (reference to the next node).

main.py
class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None
97 chars
5 lines

Now, we can create a LinkedList class that will represent the linked list. This class will have two fields - head (the first node of the list) and tail (the last node of the list).

main.py
class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
92 chars
5 lines

To add a node to the linked list, we can define a method called add_node() in the LinkedList class. This method will create a new node with the given data and add it to the end of the list.

main.py
class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        
    def add_node(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            self.tail = new_node
        else:
            self.tail.next = new_node
            self.tail = new_node
342 chars
14 lines

To traverse the linked list and print all the nodes, we can define another method called traverse() in the LinkedList class.

main.py
class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        
    def add_node(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            self.tail = new_node
        else:
            self.tail.next = new_node
            self.tail = new_node
            
    def traverse(self):
        current_node = self.head
        while current_node is not None:
            print(current_node.data)
            current_node = current_node.next
534 chars
20 lines

Now we can create an instance of the LinkedList class and add nodes to it using the add_node() method. We can also print all the nodes using the traverse() method.

main.py
my_list = LinkedList()
my_list.add_node(1)
my_list.add_node(2)
my_list.add_node(3)
my_list.traverse()
102 chars
6 lines

Output:

main.py
1
2
3
6 chars
4 lines

gistlibby LogSnag