Implementing Singly Linked List in Java

A singly linked list is a linear data structure made up of nodes, where each node contains a data field and a pointer to the next node in the sequence. Unlike arrays, linked lists do not require contiguous memory — elements can be inserted or removed at any position without shifting other elements.

In this post, we implement a full-featured singly linked list in Java that supports insertion (at first, at last, at a given position), deletion (from first, last, or a given position), search, and display.

Singly Linked List
A singly linked list — each node stores a value and a link to the next node.

Java Program: Singly Linked List

import java.io.*;

// A single node in the singly linked list
class SLLNode {
    int data;
    SLLNode next;  // Pointer to the next node; null if this is the last node

    public SLLNode(int value) {
        data = value;
        next = null;
    }
}

// Singly Linked List with insert, remove, search, and display operations
class SinglyLinkedList {
    SLLNode start = null;  // Head node; null if the list is empty

    public boolean isEmpty() {
        return start == null;
    }

    // Inserts a new node at the beginning of the list
    public void insertFirst(int value) {
        SLLNode newNode = new SLLNode(value);
        if (isEmpty()) {
            start = newNode;
        } else {
            newNode.next = start;  // New node points to old head
            start = newNode;       // Update head to new node
        }
    }

    // Inserts a new node at the end of the list
    public void insertLast(int value) {
        SLLNode newNode = new SLLNode(value);
        if (isEmpty()) {
            start = newNode;
        } else {
            SLLNode current = start;
            while (current.next != null) {
                current = current.next;  // Traverse to the last node
            }
            current.next = newNode;
        }
    }

    // Inserts a new node at the given 1-based position
    public void insertAt(int value, int position) {
        if (isEmpty() || position <= 1) {
            insertFirst(value);
            return;
        }
        SLLNode current = start;
        int index = 1;
        while (current != null) {
            if (index == position - 1) {
                SLLNode newNode = new SLLNode(value);
                newNode.next = current.next;
                current.next = newNode;
                return;
            }
            current = current.next;
            index++;
        }
        System.out.println("Position out of range - inserting at end");
        insertLast(value);
    }

    // Removes and returns the first element
    public int removeFirst() {
        if (isEmpty()) {
            System.out.println("List is empty - nothing to remove");
            return 0;
        }
        int value = start.data;
        start = start.next;
        return value;
    }

    // Removes and returns the last element
    public int removeLast() {
        if (isEmpty()) {
            System.out.println("List is empty - nothing to remove");
            return 0;
        }
        if (start.next == null) {
            int value = start.data;
            start = null;
            return value;
        }
        SLLNode current = start;
        while (current.next.next != null) {
            current = current.next;  // Stop at second-to-last node
        }
        int value = current.next.data;
        current.next = null;
        return value;
    }

    // Removes and returns the element at the given 1-based position
    public int removeAt(int position) {
        if (isEmpty()) {
            System.out.println("List is empty - nothing to remove");
            return 0;
        }
        if (position <= 1) return removeFirst();

        SLLNode current = start;
        int index = 0;
        while (current != null) {
            if (index == position - 2) {
                if (current.next == null) {
                    System.out.println("Position out of range");
                    return 0;
                }
                int value = current.next.data;
                current.next = current.next.next;
                return value;
            }
            current = current.next;
            index++;
        }
        System.out.println("Position out of range");
        return 0;
    }

    // Searches for a value and returns its 1-based position, or -1 if not found
    public int search(int value) {
        if (isEmpty()) {
            System.out.println("List is empty");
            return -1;
        }
        SLLNode current = start;
        int position = 1;
        while (current != null) {
            if (current.data == value) return position;
            current = current.next;
            position++;
        }
        return -1;
    }

    // Displays all elements from head to tail
    public void display() {
        if (isEmpty()) {
            System.out.println("List is empty");
            return;
        }
        SLLNode current = start;
        System.out.print("List: ");
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
}

public class SinglyLinkedListDemo {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        SinglyLinkedList list = new SinglyLinkedList();
        int choice;

        do {
            System.out.println();
            System.out.println("--- Singly Linked List Menu ---");
            System.out.println("1. Insert");
            System.out.println("2. Remove");
            System.out.println("3. Search");
            System.out.println("4. Display");
            System.out.println("5. Exit");
            System.out.print("Enter choice: ");
            choice = Integer.parseInt(reader.readLine());

            switch (choice) {
                case 1:
                    System.out.println("1. Insert at position");
                    System.out.println("2. Insert at first");
                    System.out.println("3. Insert at last");
                    System.out.print("Enter choice: ");
                    int insertChoice = Integer.parseInt(reader.readLine());
                    System.out.print("Enter element: ");
                    int insertValue = Integer.parseInt(reader.readLine());
                    if (insertChoice == 1) {
                        System.out.print("Enter position: ");
                        int pos = Integer.parseInt(reader.readLine());
                        list.insertAt(insertValue, pos);
                    } else if (insertChoice == 2) {
                        list.insertFirst(insertValue);
                    } else if (insertChoice == 3) {
                        list.insertLast(insertValue);
                    }
                    break;
                case 2:
                    System.out.println("1. Remove first element");
                    System.out.println("2. Remove last element");
                    System.out.println("3. Remove element at position");
                    System.out.print("Enter choice: ");
                    int removeChoice = Integer.parseInt(reader.readLine());
                    if (removeChoice == 1) {
                        System.out.println("Removed: " + list.removeFirst());
                    } else if (removeChoice == 2) {
                        System.out.println("Removed: " + list.removeLast());
                    } else if (removeChoice == 3) {
                        System.out.print("Enter position: ");
                        int pos = Integer.parseInt(reader.readLine());
                        System.out.println("Removed: " + list.removeAt(pos));
                    }
                    break;
                case 3:
                    System.out.print("Enter element to search: ");
                    int searchValue = Integer.parseInt(reader.readLine());
                    int position = list.search(searchValue);
                    System.out.println(position != -1
                        ? "Element found at position: " + position
                        : "Element not found");
                    break;
                case 4:
                    list.display();
                    break;
                case 5:
                    System.out.println("Exiting...");
                    break;
            }
        } while (choice != 5);
    }
}

How the Code Works

  1. SLLNode class — Stores an integer data value and a next pointer. The last node’s next is null.
  2. insertFirst() — Creates a new node, sets its next to the current head (start), and updates start. O(1).
  3. insertLast() — Traverses to the last node, then links it to the new node. O(n).
  4. insertAt() — Walks to the node at position pos - 1, then splices in the new node between that node and its next. O(n).
  5. removeFirst() — Saves the head’s data, advances start to start.next. O(1).
  6. removeLast() — Traverses to the second-to-last node and sets its next to null. O(n).
  7. removeAt() — Traverses to the node just before the target position and bypasses the target node. O(n).
  8. search() — Scans from head, counting positions until the value is found or the list ends. O(n).

Sample Output

/* Output
--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 1
1. Insert at position
2. Insert at first
3. Insert at last
Enter choice: 2
Enter element: 10

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 1
1. Insert at position
2. Insert at first
3. Insert at last
Enter choice: 3
Enter element: 50

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 1
1. Insert at position
2. Insert at first
3. Insert at last
Enter choice: 1
Enter element: 20
Enter position: 2

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 1
1. Insert at position
2. Insert at first
3. Insert at last
Enter choice: 3
Enter element: 90

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 4
List: 10 20 50 90 

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 3
Enter element to search: 50
Element found at position: 3

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 3
Enter element to search: 1
Element not found

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 2
1. Remove first element
2. Remove last element
3. Remove element at position
Enter choice: 1
Removed: 10

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 2
1. Remove first element
2. Remove last element
3. Remove element at position
Enter choice: 2
Removed: 90

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 4
List: 20 50 

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 1
1. Insert at position
2. Insert at first
3. Insert at last
Enter choice: 3
Enter element: 80

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 4
List: 20 50 80 

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 2
1. Remove first element
2. Remove last element
3. Remove element at position
Enter choice: 3
Enter position: 2
Removed: 50

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 4
List: 20 80 

--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 5
Exiting...
 */

See Also

Conclusion

Singly linked lists are one of the most fundamental data structures in computer science. Their dynamic size, efficient insertion at the head, and use as the building block for stacks, queues, and trees make them essential knowledge for any Java developer. The key trade-off versus arrays is the absence of random access — traversal always starts from the head.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.