allizwell.jobsdoor360.in

Introduction to Linked Lists

Data Structures and Algorithms / Linked Lists / Introduction to Linked Lists

Introduction to Linked Lists

A Linked List is a linear data structure in which elements are stored in separate memory locations called nodes. Each node contains data and a pointer that connects it to the next node. Unlike arrays, linked list elements do not need to be stored in continuous memory locations. In this topic, we will understand linked lists, their structure, working, types, advantages, disadvantages, and basic implementation using C++.

1. What Is a Linked List?

A Linked List is a collection of nodes connected through pointers. Each node stores two main things:

  • Data: The actual value stored in the node.
  • Pointer: The address of another node, usually the next node.

The first node is called the head. The last node generally points to NULL, which indicates that there are no more nodes in the list.

Example of a Linked List

Head
 |
 v
+------+------+
|  10  |   o--|---->
+------+------+
                  |
                  v
             +------+------+
             |  20  |   o--|---->
             +------+------+
                              |
                              v
                         +------+------+
                         |  30  | NULL |
                         +------+------+

In this example, the linked list contains three nodes with values 10, 20, and 30. Each node points to the next node. The final node points to NULL.

2. Why Do We Need Linked Lists?

Arrays are useful for storing collections of elements, but they have some limitations.

For example:

  • Traditional arrays have a fixed size after creation.
  • Inserting an element in the middle may require shifting other elements.
  • Deleting an element may also require shifting elements.
  • Resizing a full array may require creating a new array and copying its elements.

Linked Lists provide a different way to store data. Nodes can be created dynamically, and they can be connected or disconnected by changing pointers.

Important: Linked Lists do not require continuous memory locations. However, each node requires additional memory for storing its pointer.

3. Structure of a Linked List Node

A node is the basic building block of a linked list. In a singly linked list, a node contains data and a pointer to the next node.

C++ Node Structure

struct Node {
    int data;
    Node* next;
};

Explanation:

  • int data stores the value of the node.
  • Node* next stores the address of the next node.
  • struct Node defines the structure of a node.

The next pointer is of type Node* because it stores the address of another Node.

Creating a Node

Node* newNode = new Node();

newNode->data = 10;
newNode->next = nullptr;

This code dynamically creates a node, stores 10 in its data field, and initializes its next pointer to nullptr.

4. How Does a Linked List Work?

A linked list starts with a pointer called head. The head pointer stores the address of the first node.

Each node contains a pointer to the next node. By following these pointers, we can move from the first node to the last node.

Consider this linked list:

Head
 |
 v
[10 | next] -> [20 | next] -> [30 | NULL]
  1. Head points to the first node containing 10.
  2. The first node points to the second node containing 20.
  3. The second node points to the third node containing 30.
  4. The third node points to NULL.

To access the third node, we must start from the head and follow the next pointers until we reach it.

5. Creating a Simple Linked List in C++

Let's create a linked list containing three nodes with values 10, 20, and 30.

#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;
};

int main() {

    // Create three nodes
    Node* first = new Node();
    Node* second = new Node();
    Node* third = new Node();

    // Assign data
    first->data = 10;
    second->data = 20;
    third->data = 30;

    // Connect nodes
    first->next = second;
    second->next = third;
    third->next = nullptr;

    // Head points to the first node
    Node* head = first;

    // Print linked list
    Node* temp = head;

    while (temp != nullptr) {
        cout << temp->data << " -> ";
        temp = temp->next;
    }

    cout << "NULL" << endl;

    // Free allocated memory
    delete first;
    delete second;
    delete third;

    return 0;
}

Output

10 -> 20 -> 30 -> NULL

Code Explanation

  1. We define a Node structure containing data and a next pointer.
  2. We dynamically create three nodes using the new operator.
  3. We assign values 10, 20, and 30 to the nodes.
  4. We connect the nodes using their next pointers.
  5. We assign the address of the first node to head.
  6. We traverse the list and print each node's data.
  7. We release the dynamically allocated memory using delete.

6. Understanding the Head Pointer

The head pointer is one of the most important parts of a linked list. It stores the address of the first node.

Node* head = nullptr;

Initially, an empty linked list can have its head set to nullptr.

After creating the first node:

Node* newNode = new Node();

newNode->data = 10;
newNode->next = nullptr;

head = newNode;

Now head points to the first node of the linked list.

Remember: If the head pointer is lost and no other pointer refers to the first node, accessing the linked list becomes difficult or impossible. Always handle head carefully during insertion and deletion operations.

7. Traversing a Linked List

Traversal means visiting each node of a linked list one by one. We start from head and follow the next pointer until we reach NULL.

C++ Program for Traversal

#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;
};

void display(Node* head) {

    Node* temp = head;

    while (temp != nullptr) {

        cout << temp->data << " ";

        temp = temp->next;
    }

    cout << endl;
}

int main() {

    Node* first = new Node{10, nullptr};
    Node* second = new Node{20, nullptr};
    Node* third = new Node{30, nullptr};

    first->next = second;
    second->next = third;

    Node* head = first;

    display(head);

    delete first;
    delete second;
    delete third;

    return 0;
}

Output

10 20 30

How Traversal Works

  1. Set a temporary pointer to head.
  2. Check whether the temporary pointer is not nullptr.
  3. Print the data stored in the current node.
  4. Move the temporary pointer to the next node.
  5. Repeat until the pointer becomes nullptr.
Node* temp = head;

while (temp != nullptr) {

    cout << temp->data;

    temp = temp->next;
}

8. Types of Linked Lists

Linked Lists can be classified into different types depending on how their nodes are connected.

1. Singly Linked List

Each node contains data and a pointer to the next node. Traversal is possible only in the forward direction.

10 -> 20 -> 30 -> NULL

2. Doubly Linked List

Each node contains data, a pointer to the previous node, and a pointer to the next node. Traversal is possible in both directions.

NULL <-> 10 <-> 20 <-> 30 <-> NULL

3. Circular Linked List

In a circular linked list, the last node points back to the first node instead of pointing to NULL.

10 -> 20 -> 30
^           |
|___________|

4. Circular Doubly Linked List

This list combines doubly linked and circular linked list properties. Each node has previous and next pointers, and the first and last nodes are connected in both directions.

We will study Singly Linked List, Doubly Linked List, and Circular Linked List in detail in the upcoming topics.

9. Linked List vs Array

Arrays and linked lists both store collections of elements, but their memory organization and operations are different.

Feature Array Linked List
Memory allocation Contiguous memory locations Nodes can be stored at different memory locations
Size Traditional arrays have a fixed size Can grow or shrink dynamically
Access Direct access using an index Sequential traversal is required
Access by index O(1) O(n)
Insertion at beginning O(n) due to shifting in general O(1) when head is available
Deletion at beginning O(n) due to shifting in general O(1) when head is available
Extra memory Usually no pointer per element Requires pointer storage in each node
Cache performance Generally better due to contiguous storage Generally less cache-friendly

10. Basic Operations on Linked Lists

We can perform several operations on a linked list. These operations help us manage and modify the stored data.

Operation Description
Traversal Visit every node one by one.
Insertion Add a new node to the list.
Deletion Remove an existing node.
Searching Find a particular value in the list.
Updating Change the data stored in a node.
Reversing Change the direction of the node connections.

We will implement these operations in detail in the upcoming Linked Lists topics.

11. Time Complexity of Linked List Operations

The time complexity depends on the operation and whether we already have a pointer to the required node.

Operation Time Complexity Reason
Access by position O(n) Nodes must be traversed from the head.
Search O(n) In the worst case, every node is checked.
Traversal O(n) Every node is visited once.
Insert at beginning O(1) Only the head pointer needs to be updated.
Delete at beginning O(1) Head is moved to the next node.
Insert at end O(n) Without a tail pointer, we traverse to the last node.
Delete at end O(n) We need to find the second-last node.
Note: Insertion or deletion can take O(1) time when we already have the required node or its previous node. Finding that position may still require O(n) traversal.

12. Advantages of Linked Lists

  • Dynamic size: nodes can be added or removed when needed.
  • Efficient insertion at the beginning.
  • Efficient deletion at the beginning.
  • Does not require contiguous memory allocation.
  • Useful for implementing stacks, queues, and other data structures.
  • Can be rearranged by changing pointers instead of shifting all elements.

13. Disadvantages of Linked Lists

  • Extra memory is required for pointers.
  • No direct random access using an index.
  • Searching generally takes O(n) time.
  • Pointer management makes implementation more complex.
  • Nodes may have poor cache locality compared with arrays.
  • Incorrect pointer handling can cause memory leaks or invalid memory access.

14. Applications of Linked Lists

Linked Lists are used in several areas of computer science and software development.

  • Stacks: A linked list can be used to implement a stack.
  • Queues: Linked lists can implement dynamic queues.
  • Browser navigation: Doubly linked lists can represent previous and next navigation.
  • Music playlists: Songs can be connected using linked list nodes.
  • Undo and redo: Linked structures can help maintain navigation between states.
  • Memory management: Linked lists can organize free memory blocks.
  • LRU Cache: A doubly linked list is commonly combined with a hash map to implement an LRU cache.

15. Common Mistakes While Learning Linked Lists

1. Forgetting to Initialize the Next Pointer

Always initialize the next pointer when creating a node. For a new final node, use nullptr.

Node* newNode = new Node();

newNode->data = 10;
newNode->next = nullptr;

2. Losing the Head Pointer

Do not move the head pointer directly during traversal. Use a temporary pointer instead.

Node* temp = head;

while (temp != nullptr) {
    cout << temp->data;
    temp = temp->next;
}

3. Accessing a Null Pointer

Before accessing a node's data or next pointer, make sure the pointer is not nullptr.

4. Incorrect Pointer Connections

When inserting or deleting nodes, pointer connections must be updated in the correct order. Otherwise, parts of the list may become inaccessible.

5. Forgetting to Release Dynamic Memory

Nodes created using new should be properly released when they are no longer needed. Otherwise, memory leaks can occur.

16. Interview Questions

Q1. What is a Linked List?

A Linked List is a linear data structure made up of nodes. Each node stores data and one or more pointers that connect it to other nodes.

Q2. What is a node?

A node is an individual element of a linked list. In a singly linked list, it contains data and a pointer to the next node.

Q3. What is the head pointer?

The head pointer stores the address of the first node of a linked list.

Q4. What does NULL or nullptr represent?

It represents the absence of a valid next node. In a standard singly linked list, the last node points to nullptr.

Q5. Is linked list memory contiguous?

No. Linked list nodes can be stored at different memory locations. Pointers connect these nodes.

Q6. Why is accessing an element in a linked list O(n)?

Because we generally need to start from the head and follow pointers until we reach the required position.

Q7. What is the difference between an array and a linked list?

Arrays store elements in contiguous memory and support direct index-based access. Linked lists store elements in separate nodes connected using pointers.

Q8. Can a linked list grow dynamically?

Yes. New nodes can be allocated when needed, and existing nodes can be removed.

Q9. What are the main types of linked lists?

The main types are singly linked lists, doubly linked lists, circular linked lists, and circular doubly linked lists.

Q10. What is the time complexity of traversing a linked list?

Traversal takes O(n) time because every node is visited once.

17. Practice Problems

  1. Create a node using a C++ structure.
  2. Create a linked list containing three nodes.
  3. Print all elements of a linked list.
  4. Count the total number of nodes.
  5. Search for a given value in a linked list.
  6. Find the first and last nodes of a linked list.
  7. Calculate the sum of all node values.
  8. Find the maximum and minimum values in a linked list.
  9. Compare array traversal with linked list traversal.
  10. Create an empty linked list and insert its first node.

18. Summary

  • A Linked List is a linear data structure made up of nodes.
  • Each node stores data and pointer information.
  • The head pointer stores the address of the first node.
  • The last node of a standard singly linked list points to nullptr.
  • Linked list nodes do not need contiguous memory locations.
  • Traversal and searching generally take O(n) time.
  • Insertion and deletion at the beginning take O(1) time.
  • The main types include singly, doubly, and circular linked lists.
Key Takeaway: A Linked List connects individual nodes using pointers. Understanding nodes, the head pointer, and traversal is essential before learning insertion, deletion, reversal, cycle detection, and other linked list algorithms.
Scroll to Top