WikiGalaxy

Personalize

Introduction to Singly Linked List

Concept of Singly Linked List:

A singly linked list is a linear data structure consisting of nodes where each node contains data and a reference (or link) to the next node in the sequence. It allows for dynamic memory allocation, which means the list can grow or shrink as needed.

Structure of Node:

Each node in a singly linked list consists of two parts: the data part and the reference to the next node.

Advantages:

Efficient insertion and deletion of elements, especially when compared to arrays, as it does not require shifting of elements.

Disadvantages:

It does not allow direct access to elements, which means accessing an element requires traversal from the head node.

Real-World Applications:

Used in applications where dynamic memory allocation and efficient insertions and deletions are required, such as in implementing stacks, queues, and adjacency lists for graphs.

    Step 1: Initialize a head node pointing to null.
    Step 2: Create a new node and assign data to it.
    Step 3: Point the next of the new node to null.
    Step 4: If the list is empty, set the head to the new node.
    Step 5: Else, traverse the list to find the last node and point its next to the new node.
  

      class Node {
          int data;
          Node next;
          Node(int d) { data = d; next = null; }
      }

      class LinkedList {
          Node head;
          public void addNode(int data) {
              Node newNode = new Node(data);
              if (head == null) {
                  head = newNode;
              } else {
                  Node current = head;
                  while (current.next != null) {
                      current = current.next;
                  }
                  current.next = newNode;
              }
          }
      }
    

Detailed Explanation of Code:

The code defines a Node class with data and reference to the next node. The LinkedList class manages the nodes, allowing for the addition of new nodes to the end of the list.

Node Class:

The Node class acts as a blueprint for creating new nodes with data and a pointer to the next node.

LinkedList Class:

The LinkedList class contains a head node and methods to add new nodes. It traverses the list to add new nodes at the end.

Adding Nodes:

The addNode method checks if the list is empty. If so, it sets the head to the new node. Otherwise, it traverses to the end of the list to add the new node.

Console Output:

Node added to the list

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025