algoadvance

Design your implementation of the linked list. You can choose to use a singly or doubly linked list.

A node in a singly linked list should have two attributes:

Implement the MyLinkedList class:

Clarifying Questions

  1. Type of Linked List: Should we implement a singly linked list or can we opt for a doubly linked list?
    • We’ll proceed with a singly linked list for simplicity unless otherwise specified.
  2. Edge Cases: Should we handle edge cases such as adding/deleting from an empty list?
    • Yes, edge cases should be handled.

Code

class MyLinkedList:
    class ListNode:
        def __init__(self, val=0):
            self.val = val
            self.next = None
    
    def __init__(self):
        self.head = None
        self.size = 0

    def get(self, index):
        if index < 0 or index >= self.size:
            return -1
        current = self.head
        for _ in range(index):
            current = current.next
        return current.val

    def addAtHead(self, val):
        new_node = self.ListNode(val)
        new_node.next = self.head
        self.head = new_node
        self.size += 1

    def addAtTail(self, val):
        new_node = self.ListNode(val)
        if not self.head:
            self.head = new_node
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node
        self.size += 1

    def addAtIndex(self, index, val):
        if index < 0 or index > self.size:
            return
        if index == 0:
            self.addAtHead(val)
        else:
            new_node = self.ListNode(val)
            current = self.head
            for _ in range(index - 1):
                current = current.next
            new_node.next = current.next
            current.next = new_node
            self.size += 1

    def deleteAtIndex(self, index):
        if index < 0 or index >= self.size:
            return
        if index == 0:
            self.head = self.head.next
        else:
            current = self.head
            for _ in range(index - 1):
                current = current.next
            current.next = current.next.next
        self.size -= 1

Strategy

  1. Node Class: We define an inner class ListNode to represent each node in the linked list.
  2. Initialization: The MyLinkedList class maintains a reference to the head of the list and a size counter.
  3. Get Method: Traverse the list until the index is reached, then return the value of that node. Return -1 for invalid indices.
  4. Add Methods:
    • addAtHead: New node becomes the new head.
    • addAtTail: Traverse to the end of the list, then append the new node.
    • addAtIndex: Traverse to one node before the specified index, adjust pointers to insert the new node.
  5. Delete Method: Traverse to one node before the specified index, adjust pointers to skip the node to be deleted.

Time Complexity

Try our interview co-pilot at AlgoAdvance.com