Linked Lists Operations

COSC 2306 - Singly Linked List Visualizer

HEAD
None

Controls

# Linked List initialized
# head = None

Data Structure Concepts

insert() - $O(1)$ Adding a new node is a two-step process:
  1. Set newnode.next to point to the current head.
  2. Update head to point to the newnode.
append() - $O(n)$ Requires traversing the entire list:
  • Start at the head.
  • Walk through the list until current.next == None.
  • Set current.next to the newnode.
pop() - $O(1)$ Removing the first node:
  • If list is empty, return None.
  • Otherwise, shift head: head = head.next.
  • The old head is garbage collected.
remove(item) - $O(n)$ Challenge: Cannot go backwards! Solution: Use 2 external references.
  • Use current and previous to track nodes.
  • If item is at head: head = current.next.
  • Otherwise: previous.next = current.next.
Python Implementation Details
                            
class Node:
    def __init__(self, initdata):
        self.data = initdata
        self.next = None

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

    def insert(self, value):
        newnode = Node(value)
        newnode.next = self.head
        self.head = newnode

    def append(self, item):
        current = self.head
        if current == None:
            self.head = Node(item)
        else:
            while current.next != None:
                current = current.next
            current.next = Node(item)

    def pop(self):
        if self.head == None:
            return None
        self.head = self.head.next

    def remove(self, item):
        current = self.head
        previous = None
        found = False

        while not found and current != None:
            if current.data == item:
                found = True
            else:
                previous = current
                current = current.next
        
        if current == None:
            return # item not found
            
        if previous == None:
            self.head = current.next
        else:
            previous.next = current.next