Keep The Ball Rolling

Writting about things around

4 of 100 days of code: Linked Lists

Starting on day 4th is not what I was expecting. Normally when you try to improve your discipline you want to start with day 1, but is better than nothing I guess. So, I am re-studying DSA and algorithms, and practicing some basic operations with linked lists.

Here is the class which I will use for implement the operations:

from typing import Optional, Any

class Node:
    def __init__(self, val: Any, next: Optional["Node"]=None):
        self.val = val
        self.next = next

class SinglyLinkedList:
    def __init__(self):
        self.head: Optional[Node] = None
        self.size = 0

So, the first one is the “Insert at head” or insert at start, or beginning. Using this class we have val, next, and size, well size for the linked list, it's obvious what that means.

def insert_at_head(self, val: Any) -> None:
        node = Node(val, next=self.head)
        self.head = node
        self.size += 1

We need to make the val is node, and object of the class, so we can have the val, and next attributes. And don't forget to increment the size.