Linked list append in Python

Here in this tutorial, we will learn how to append a linked list in Python. Append means to add something to an already defined collection like a/an list/array or linked list in Python.

First, let us look at the base Node class, which will give us an idea of the nodes already defined in the linked list.

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

I have named this class Node which indicates a specific node. The terms data and next here refer to the value of data stored in the node and the reference of the next node respectively.

The reference to the next node is equal to None when a particular node is defined.

Append Linked List

def appendLinkedList(head,ele):
    if head == None:
        head = Node(ele)
        return head
    
    else:   
        curr = head
        while curr.next:
            curr = curr.next
        
        curr.next = Node(ele)
    
        return head

Here we have defined a function called appendLinkedList with the following parameters:

  • head: indicating the starting element of the linked list.
  • ele: indicating the value of the new element that is to be inserted.

Firstly, we will check if the linked list is already empty, if it is then we will assign the head to the new element and return it.

Else, we will take a variable called curr(current) which is equal to head at the moment; following this, we will continue with a while loop which will run till the next of curr is not equal to None; the moment this happens the while loop will stop.

Then we will set the reference of the next element of curr to be equal to the new node defined with the value given and in the end the head element will be returned.

Thus, we have appended the new element to the linked list.

Leave a Reply

Your email address will not be published.