Categories: Data Structure

Introduction to Singly Linked List

Singly Linked List

Singly Linked List is a linear and connected data structure made of Nodes. Each node is composed of a variable data where its content (actual value) is stored and a pointer to the next Node (next node location) on the list. The Linked List has a pointer to the first element of this Node sequence and may also have another pointer to the last Node to make operations at the far end less time-consuming. You can also store a length variable to store the total length.

Advantages over Arrays

  • Size of a linked list is not fixed (dynamic size)
  • Deleting and adding an element is not expensive compared to an array

Drawbacks

  • Elements can be accessed sequentially not randomly compared to an array
  • Extra memory allocation needs to be done for pointers which connects elements in a linked list

Time Complexity

OperationAverageWorst
AccessO(n)O(n)
SearchO(n)O(n)
InsertionO(1)O(1)
DeletionO(1)O(1)

Example in C++

class LinkedList {
    Node head;      // Pointer to the first element
    Node tail;      // Optional. Points to the last element

    int length;     // Optional

    class Node {
        int data;   // Node data. Can be int, string, float, templates, etc
        Node next;  // Pointer to the next node on the list
    }
}

Recent Posts

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

2 days ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 weeks ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

1 month ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 month ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

2 months ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

2 months ago