#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Linked Lists

Singly Linked List

A Singly Linked List is a linear data structure made up of nodes, where each node contains data and a reference (pointer) to the next node in the sequence. Unlike arrays, elements are not stored contiguously in memory.

Node Structure

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

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

    def append(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        current = self.head
        while current.next:
            current = current.next
        current.next = new_node

    def delete(self, key):
        current = self.head
        prev = None
        while current and current.data != key:
            prev = current
            current = current.next
        if current is None:
            return
        if prev is None:
            self.head = current.next
        else:
            prev.next = current.next

    def traverse(self):
        values = []
        current = self.head
        while current:
            values.append(current.data)
            current = current.next
        return values

Complexity

OperationTime
Access by indexO(n)
Insert at headO(1)
Insert at tail (no tail pointer)O(n)
DeleteO(n)

Advantages & Disadvantages

  • Advantage: dynamic size, efficient insertions/deletions at the head.
  • Disadvantage: no direct/random access; traversal is required to reach a given position, and extra memory is used for the next pointer.

Applications

  • Implementing stacks and queues.
  • Dynamic memory allocation systems.
  • Building blocks for more advanced structures like hash maps (chaining) and graphs (adjacency lists).

Inserting at the Head and at a Given Position

Inserting at the head is the operation where a linked list beats an array, because nothing has to shift. Inserting at a position needs a walk to the node just before it.

def insert_at_head(self, data):
    node = Node(data)
    node.next = self.head      # new node points to the old first node
    self.head = node           # head now points to the new node

def insert_at(self, index, data):
    if index == 0:
        return self.insert_at_head(data)
    current = self.head
    for _ in range(index - 1):
        if current is None:
            raise IndexError("index out of range")
        current = current.next
    if current is None:
        raise IndexError("index out of range")
    node = Node(data)
    node.next = current.next   # link the new node first...
    current.next = node        # ...then attach it

The order of the last two lines matters. If you set current.next = node first, you lose the reference to the rest of the list.

Reversing a List: Step-by-Step Trace

Reversal is one of the most asked linked list questions. You walk the list once and flip each pointer, using three variables.

def reverse(self):
    prev = None
    current = self.head
    while current:
        nxt = current.next     # remember the rest of the list
        current.next = prev    # flip the pointer
        prev = current         # move prev forward
        current = nxt          # move current forward
    self.head = prev
StepprevcurrentReversed part
StartNone1(empty)
After 1st loop121 → None
After 2nd loop232 → 1 → None
After 3rd loop3None3 → 2 → 1 → None

It runs in linear time and uses constant extra memory.

Two-Pointer Techniques: Middle Node and Cycle Detection

Moving one pointer one step and another two steps at a time solves several problems in a single pass.

def middle(self):
    slow = fast = self.head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow.data if slow else None

def has_cycle(self):
    slow = fast = self.head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False

When the fast pointer reaches the end, the slow one is in the middle. If the list accidentally loops back on itself, the fast pointer eventually laps the slow one and they meet. This is known as Floyd's cycle detection.

Both pointers start at the head, and the loop condition checks fast and fast.next so the fast pointer never jumps past the end. For a list with an even number of nodes, this version returns the second of the two middle nodes. Interviewers sometimes ask for the first one instead; starting fast at head.next gives that result. Being able to explain such small changes shows you understand the technique rather than having memorised it.

Bugs to Avoid and a Revision List

  • Not handling an empty list (head is None) before reading head.next.
  • Forgetting to update head after deleting or reversing.
  • Losing the rest of the list by overwriting next before saving it.
  • Using a linked list for heavy index-based access, where an array or Python list is faster.

Practise these until they are automatic

  1. Insert at head, tail and a position.
  2. Delete by value and by position.
  3. Reverse iteratively, then try it recursively.
  4. Find the middle and detect a cycle with two pointers.
  5. Merge two sorted lists into one.