Open In App

How to create linked list?

Last Updated : 30 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will explore the process of creating a linked list. A linked list consists of nodes, each containing data and a reference to the next node. We will walk through the steps of defining the node structure, initializing the head of the list, creating new nodes, and linking these nodes to form the list. By the end of this article, you will have a clear understanding of how to implement a linked list.

Singly-Linked-List

LinkedList Structure

A LinkedList is a linear data structure where each element is a separate object called a node. Each node contains two fields: one for data and one for the reference to the next node. The first node is called the head. If the LinkedList is empty, the head is a null reference.

How to create linked list?

A linked list is a dynamic data structure that consists of nodes. Each node contains two fields: one for storing data and the other for storing the address of the next node in the list.

Here’s how you can create a linked list:

Step 1: Define the Node Structure

First, we need to define the structure of a node in the linked list. Each node will contain some data and a pointer to the next node.

C++
struct Node {
    int data; // The data stored in the node
    Node* next; // Pointer to the next node
};
Java
class Node {
    int data; // The data stored in the node
    Node next; // Pointer to the next node
}
Python
class Node:
    def __init__(self, data):
        self.data = data  # The data stored in the node
        self.next = None   # Pointer to the next node
JavaScript
class Node {
    constructor(data) {
        this.data = data;  // The data stored in the node
        this.next = null;  // Pointer to the next node
    }
}

Step 2: Initialize the Head of the List

The head of the list is the first node in the list. Initially, the list is empty, so the head is a null pointer.

C++
Node* head = nullptr;
Java
Node head = null;
Python
head = None
JavaScript
let head = null;

Step 3: Create New Nodes

To add elements to the list, we create new nodes. Each new node should be dynamically allocated using the new keyword.

C++
Node* newNode = new Node();
Java
Node newNode = new Node();
Python
newNode = Node()
JavaScript
let newNode = new Node();


After creating a new node, we can set the data field and initialize the next pointer to null.

C++
newNode->data = 1; // Replace 1 with the actual data
newNode->next = nullptr;
Java
newNode.data = 1; // Replace 1 with the actual data
newNode.next = null;
Python
newNode.data = 1  # Replace 1 with the actual data
newNode.next = None
JavaScript
newNode.data = 1;  // Replace 1 with the actual data
newNode.next = null;

Step 4: Link the Nodes

If the list is not empty, we need to traverse the list to find the last node and update its next pointer.

C++
if (head == nullptr) {
    // The list is empty, so the new node is the head of the list
    head = newNode;
} else {
    // The list is not empty, traverse the list to find the last node
    Node* temp = head;
    while (temp->next != nullptr) {
        temp = temp->next;
    }
    // Now temp points to the last node, link the new node
    temp->next = newNode;
}
Java
if (head == null) {
    // The list is empty, so the new node is the head of the list
    head = newNode;
} else {
    // The list is not empty, traverse the list to find the last node
    Node temp = head;
    while (temp.next != null) {
        temp = temp.next;
    }
    // Now temp points to the last node, link the new node
    temp.next = newNode;
}
Python
if head is None:
    # The list is empty, so the new node is the head of the list
    head = newNode
else:
    # The list is not empty, traverse the list to find the last node
    temp = head
    while temp.next is not None:
        temp = temp.next
    # Now temp points to the last node, link the new node
    temp.next = newNode
#this code ios cpntributed by MOnu.
JavaScript
if (head === null) {
    // The list is empty, so the new node is the head of the list
    head = newNode;
} else {
    // The list is not empty, traverse the list to find the last node
    let temp = head;
    while (temp.next !== null) {
        temp = temp.next;
    }
    // Now temp points to the last node, link the new node
    temp.next = newNode;
}

Complete Implemenatation LinkedList:

C++
#include <bits/stdc++.h>
using namespace std;

// Define the Node structure
struct Node {
    int data; // The data stored in the node
    Node* next; // Pointer to the next node
};

int main()
{

    // Initialize the head of the list
    Node* head = nullptr;

    // Create new nodes and add them to the list
    for (int i = 1; i <= 5; i++) {
        Node* newNode = new Node();
        newNode->data = i; // Replace i with the actual data
        newNode->next = nullptr;

        // Link the nodes
        if (head == nullptr) {

            // The list is empty, so the new node is the
            // head of the list
            head = newNode;
        }
        else {

            // The list is not empty, traverse the list to
            // find the last node
            Node* temp = head;
            while (temp->next != nullptr) {
                temp = temp->next;
            }

            // Now temp points to the last node, link the
            // new node
            temp->next = newNode;
        }
    }

    // Print the list
    Node* temp = head;
    while (temp != nullptr) {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << endl;

    // Free up the memory
    while (head != nullptr) {
        Node* temp = head;
        head = head->next;
        delete temp;
    }

    return 0;
}
Java
// Import necessary libraries
import java.util.*;

// Define the Node class
class Node {
    int data; // The data stored in the node
    Node next; // Reference to the next node

    // Node constructor
    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}

public class Main {
    public static void main(String[] args) {

        // Initialize the head of the list
        Node head = null;

        // Create new nodes and add them to the list
        for (int i = 1; i <= 5; i++) {
            Node newNode = new Node(i); // Replace i with the actual data

            // Link the nodes
            if (head == null) {
                // The list is empty, so the new node is the
                // head of the list
                head = newNode;
            } else {
                // The list is not empty, traverse the list to
                // find the last node
                Node temp = head;
                while (temp.next != null) {
                    temp = temp.next;
                }

                // Now temp points to the last node, link the
                // new node
                temp.next = newNode;
            }
        }

        // Print the list
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println();

        // No explicit memory deallocation is needed in Java
        // The Java Garbage Collector will automatically free up the memory
    }
}
Python
# Define the Node class
class Node:
    def __init__(self, data=None):
        self.data = data  # The data stored in the node
        self.next = None  # Pointer to the next node

# Initialize the head of the list
head = None

# Create new nodes and add them to the list
for i in range(1, 6):
    new_node = Node(i)  # Replace i with the actual data

    # Link the nodes
    if head is None:
        # The list is empty, so the new node is the
        # head of the list
        head = new_node
    else:
        # The list is not empty, traverse the list to
        # find the last node
        temp = head
        while temp.next is not None:
            temp = temp.next

        # Now temp points to the last node, link the
        # new node
        temp.next = new_node

# Print the list
temp = head
while temp is not None:
    print(temp.data, end=" ")
    temp = temp.next
print()
JavaScript
// Define the Node class
class Node {
    constructor(data) {
        this.data = data; // The data stored in the node
        this.next = null; // Pointer to the next node
    }
}

// Main function
function main() {
    // Initialize the head of the list
    let head = null;

    // Create new nodes and add them to the list
    for (let i = 1; i <= 5; i++) {
        let newNode = new Node(i); // Replace i with the actual data

        // Link the nodes
        if (head === null) {
            // The list is empty, so the new node is the head of the list
            head = newNode;
        } else {
            // The list is not empty, traverse the list to find the last node
            let temp = head;
            while (temp.next !== null) {
                temp = temp.next;
            }

            // Now temp points to the last node, link the new node
            temp.next = newNode;
        }
    }

    // Print the list
    let temp = head;
    let listStr = "";
    while (temp !== null) {
        listStr += temp.data + " ";
        temp = temp.next;
    }
    console.log(listStr.trim());

    // Free up the memory
    while (head !== null) {
        let temp = head;
        head = head.next;
        temp = null;
    }
}

// Call the main function
main();

Output
1 2 3 4 5 


Conclusion

Creating a LinkedList involves several steps: defining the Node structure, initializing the LinkedList, and implementing methods to add and traverse nodes. While the implementation can vary depending on the programming language, the fundamental concepts remain the same. Understanding these steps is crucial for anyone learning data structures and algorithms.




Similar Reads

Create new linked list from two given linked list with greater element at each node
Given two linked list of the same size, the task is to create a new linked list using those linked lists. The condition is that the greater node among both linked list will be added to the new linked list.Examples: Input: list1 = 5-&gt;2-&gt;3-&gt;8 list2 = 1-&gt;7-&gt;4-&gt;5 Output: New list = 5-&gt;7-&gt;4-&gt;8 Input: list1 = 2-&gt;8-&gt;9-&gt;
8 min read
Create a linked list from two linked lists by choosing max element at each position
Given two linked list of equal sizes, the task is to create new linked list using those linked lists where at every step, the maximum of the two elements from both the linked lists is chosen and the other is skipped. Examples: Input: list1 = 5 -&gt; 2 -&gt; 3 -&gt; 8 -&gt; NULL list2 = 1 -&gt; 7 -&gt; 4 -&gt; 5 -&gt; NULL Output: 5 -&gt; 7 -&gt; 4
11 min read
Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node. Introduction to Doubly linked list : A Doubly Linked List (D
2 min read
Convert Singly Linked List to XOR Linked List
Prerequisite: XOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node's address. Given a singly linked list, the task is to convert the gi
9 min read
Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
Given a Linked List of even number of nodes, the task is to generate a new Linked List such that it contains the maximum difference of squares of node values in decreasing order by including each node in a single pair. Examples: Input: 1 -&gt; 6 -&gt; 4 -&gt; 3 -&gt; 5 -&gt;2Output: 35 -&gt; 21 -&gt; 7Explanation:The difference between squares of 6
11 min read
XOR linked list- Remove first node of the linked list
Given an XOR linked list, the task is to remove the first node of the XOR linked list. Examples: Input: XLL = 4 &lt; – &gt; 7 &lt; – &gt; 9 &lt; – &gt; 7 Output: 7 &lt; – &gt; 9 &lt; – &gt; 7 Explanation: Removing the first node of the XOR linked list modifies XLL to 7 &lt; – &gt; 9 &lt; – &gt; 7 Input: XLL = NULL Output: List Is Empty Approach: Th
11 min read
Remove all occurrences of one Linked list in another Linked list
Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 3 -&gt; 4, head2 = 3 -&gt; 4Output: 2 -&gt; 5Explanation: After removing all occurrences of 3 -&gt; 4 in head1 output is 2 -&gt; 5. Input: head1 = 3 -&gt; 6 -&gt; 9 -&gt; 8 -
9 min read
Insert a linked list into another linked list
Given two linked lists, list1 and list2 of sizes m and n respectively. The task is to remove list1's nodes from the ath node to the bth node and insert the list2 in their place.Examples: Input: list1: 10-&gt;11-&gt;12-&gt;13-&gt;14-&gt;15, list2: 100-&gt;101-&gt;102-&gt;103, a = 3, b = 4Output: 10-&gt;11-&gt;12-&gt;100-&gt;101-&gt;102-&gt;103-&gt;1
13 min read
Count occurrences of one linked list in another Linked List
Given two linked lists head1 and head2, the task is to find occurrences of head2 in head1. Examples: Input: Head1 = 1-&gt;2-&gt;3-&gt;2-&gt;4-&gt;5-&gt;2-&gt;4, Head2 = 2-&gt;4Output: Occurrences of head2 in head1: 2 Input: Head1 = 3-&gt;4-&gt;1-&gt;5-&gt;2, Head2 = 3-&gt;4Output: Occurrences of Head2 in Head1: 1 Approach 1: To solve the problem us
15 min read
Merge a linked list into another linked list at alternate positions
Given two linked lists, insert nodes of second list into first list at alternate positions of first list. For example, if first list is 5-&gt;7-&gt;17-&gt;13-&gt;11 and second is 12-&gt;10-&gt;2-&gt;4-&gt;6, the first list should become 5-&gt;12-&gt;7-&gt;10-&gt;17-&gt;2-&gt;13-&gt;4-&gt;11-&gt;6 and second list should become empty. The nodes of se
11 min read