How to implement a linked list in Java

How to Implement a Linked List in Java: Insert, Delete, Search, and Swap (Assignment Guide)

If your Java class just assigned a linked list and you are staring at the instructions wondering where to even start, you are in the right place. Linked lists are one of the first real data structures students build by hand, and almost every computer science course uses them to test whether you truly understand objects, references, and pointers. The good news is that once you see the pattern, a linked list assignment becomes a set of small, repeatable steps.

This guide is written for students. It explains what a linked list is in plain English, shows you how to build one from scratch, and walks through every operation a professor is likely to grade: insert, delete, search, swap, and display. Every code example here was compiled and run on a real Java machine, so you can paste it into VS Code, IntelliJ, Eclipse, or NetBeans and watch it work. We will also cover singly, doubly, and circular linked lists, a full worked assignment, the pointer mistakes that cost the most marks, and the viva questions professors ask when you present your work.

What Is a Linked List in Java?

A linked list is a chain of small objects called nodes. Each node holds two things: a piece of data, and a link (a reference) to the next node in the chain. The first node is called the head. The last node links to null, which marks the end of the list.

Picture a treasure hunt. Each clue gives you an answer and tells you where the next clue is. The head is your first clue, and you follow the links from one node to the next until a node points to nothing, which means the hunt is over. That is exactly how a linked list works.

This is different from an array. An array stores everything in one solid block of memory with a fixed size. A linked list spreads its nodes around memory and connects them with links, so it can grow and shrink easily. That flexibility is the main reason professors ask you to build one.

Build Your Own vs Java's Built-in LinkedList: Which Does Your Assignment Want?

Before you write a single line, read your assignment sheet carefully, because there are two completely different tasks that both get called "linked list," and picking the wrong one can cost you every point.

The first kind asks you to build the linked list yourself, with your own Node class and your own methods. Many assignments say something like "you are not permitted to use Java's built-in collection classes" and warn that using java.util.LinkedList will result in a zero. If your instructions mention a Node class, a head reference, or writing your own insert and delete methods, this is your task, and this guide covers exactly that.

The second kind asks you to use Java's built-in LinkedList class and just call its ready-made methods like add() and remove(). Some assignments say the opposite of the first kind: do not write your own list, and if your code has anything that looks like a Node, you are on the wrong track. This task is about learning to use a collection, not build one.

So the very first step of any linked list assignment is to figure out which of these two you have. If the sheet is unclear, ask your instructor. Getting this wrong is the single most common way students lose a whole assignment, and no amount of good code fixes it. The rest of this guide focuses on the build-your-own version, since that is the harder and more commonly graded one.

The Node Class: The Building Block of Every Linked List

Everything starts with the node. A node is a tiny class that stores one value and a link to the next node. Here is the simplest version, holding an int.

Node.java
static class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;   // a brand new node links to nothing yet
    }
}

That Node next field is the important part. It is a reference to another Node, which is how nodes chain together. When you create a node, its next starts as null until you link it to something.

Setting Up the Linked List Class

The linked list class itself is surprisingly small. It only needs to remember where the chain begins, which is the head.

LinkedList.java
class LinkedList {
    static class Node {
        int data;
        Node next;
        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }

    Node head;   // the first node; null means the list is empty
}

That single head field is the doorway to your entire list. Every operation you write will start from head and follow the links. If you ever lose track of head, you lose the whole list, so protect it carefully.

How to Insert a Node in a Linked List

Insertion is where most linked list assignments begin. There are three common versions, and many assignments ask for all three.

Insert at the Start

Adding to the front is the quickest insert. You point the new node at the current head, then make the new node the head.

LinkedList.java (Insert Start)
public void insertAtStart(int data) {
    Node newNode = new Node(data);
    newNode.next = head;   // new node points to the old first node
    head = newNode;        // new node becomes the head
}

Insert at the End

To add to the end, you walk the list until you reach the last node (the one whose next is null), then link it to the new node. Watch the empty-list case, where the new node simply becomes the head.

LinkedList.java (Insert End)
public void insertAtEnd(int data) {
    Node newNode = new Node(data);
    if (head == null) {        // empty list
        head = newNode;
        return;
    }
    Node current = head;
    while (current.next != null) {   // walk to the last node
        current = current.next;
    }
    current.next = newNode;    // link the last node to the new one
}

Insert at a Position

This is the version professors love, because it forces you to handle edge cases. The instructions often look like "insert 50 at position 3," and they usually want you to handle bad positions gracefully. In the code below, positions count from 0, so position 0 is the front.

LinkedList.java (Insert Position)
public void insertAtPosition(int data, int position) {
    if (position < 0) {
        System.out.println("Invalid position: " + position);
        return;
    }
    if (position == 0) {
        insertAtStart(data);
        return;
    }
    Node newNode = new Node(data);
    Node current = head;
    int index = 0;
    // stop at the node just before the target position
    while (current != null && index < position - 1) {
        current = current.next;
        index++;
    }
    if (current == null) {     // position is past the end
        System.out.println("Position " + position + " is out of range.");
        return;
    }
    newNode.next = current.next;
    current.next = newNode;
}

Notice the two checks: one for a negative position, and one for a position past the end. Handling these "invalid position" cases is often worth marks on its own, because a rubric will test what happens when you feed it a bad number.

How to Delete a Node in a Linked List

Deleting is the mirror image of inserting. You find the node you want gone, then link the node before it straight to the node after it, which skips the target out of the chain.

LinkedList.java (Delete)
public boolean delete(int target) {
    if (head == null) {
        return false;          // empty list, nothing to delete
    }
    if (head.data == target) { // deleting the head
        head = head.next;
        return true;
    }
    Node current = head;
    while (current.next != null && current.next.data != target) {
        current = current.next;
    }
    if (current.next == null) {
        return false;          // value was not found
    }
    current.next = current.next.next;   // skip over the deleted node
    return true;
}

The trick here is that you stop at the node before the one you want to delete, so you can rewire its next. That is why the loop checks current.next.data instead of current.data. Deleting the head is a special case, since there is no node before it.

How to Search a Linked List

Searching means walking the list from the head and checking each node until you find the value or run off the end.

LinkedList.java (Search)
public boolean search(int target) {
    Node current = head;
    while (current != null) {
        if (current.data == target) {
            return true;
        }
        current = current.next;
    }
    return false;
}

This same walk-the-list pattern (start at head, move with current = current.next, stop at null) is the backbone of almost every linked list method you will write.

How to Swap Two Nodes

Some assignments ask you to rearrange the list by swapping two values. The simplest, safest way for a homework task is to find both nodes and swap the data they hold.

LinkedList.java (Swap)
public boolean swap(int value1, int value2) {
    Node node1 = null;
    Node node2 = null;
    Node current = head;
    while (current != null) {
        if (current.data == value1 && node1 == null) {
            node1 = current;
        }
        if (current.data == value2 && node2 == null) {
            node2 = current;
        }
        current = current.next;
    }
    if (node1 == null || node2 == null) {
        return false;          // one of the values was missing
    }
    int temp = node1.data;     // swap the stored values
    node1.data = node2.data;
    node2.data = temp;
    return true;
}

If your assignment specifically requires swapping the nodes themselves (rewiring the links) rather than the values, that is trickier and involves several pointer changes. For most courses, swapping the data is accepted and far less error-prone.

How to Display and Traverse a Linked List

Almost every assignment asks you to print the list, both to see your results and because the grader compares your output to a sample. Traversing just means walking every node.

LinkedList.java (Display)
public void display() {
    Node current = head;
    while (current != null) {
        System.out.print(current.data + " -> ");
        current = current.next;
    }
    System.out.println("null");
}

Putting It All Together

Here is a main method that runs every operation above, along with the real output it produces.

LinkedListDemo.java
public class LinkedListDemo {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();

        list.insertAtEnd(10);
        list.insertAtEnd(20);
        list.insertAtEnd(30);
        list.insertAtEnd(40);
        System.out.print("Start:             ");
        list.display();

        list.insertAtPosition(50, 3);
        System.out.print("Insert 50 at 3:    ");
        list.display();

        list.insertAtStart(5);
        System.out.print("Insert 5 at front: ");
        list.display();

        list.delete(20);
        System.out.print("Delete 20:         ");
        list.display();

        System.out.println("Search 30:         " + list.search(30));
        System.out.println("Search 99:         " + list.search(99));

        list.swap(10, 40);
        System.out.print("Swap 10 and 40:    ");
        list.display();
    }
}
Console Output:
Start:             10 -> 20 -> 30 -> 40 -> null
Insert 50 at 3:    10 -> 20 -> 30 -> 50 -> 40 -> null
Insert 5 at front: 5 -> 10 -> 20 -> 30 -> 50 -> 40 -> null
Delete 20:         5 -> 10 -> 30 -> 50 -> 40 -> null
Search 30:         true
Search 99:         false
Swap 10 and 40:    5 -> 40 -> 30 -> 50 -> 10 -> null

Save all of this in one file named LinkedListDemo.java (the public class name must match the file name), then run it. It works the same in VS Code, IntelliJ, Eclipse, and NetBeans.

Singly, Doubly, and Circular Linked Lists: What Is the Difference?

The list above is a singly linked list, where each node points only to the next one. Assignments often ask for two other types, so here is what changes.

Doubly Linked List

In a doubly linked list, each node has two links: next and prev. That extra prev link lets you walk the list backward as well as forward.

DoublyLinkedList.java
class DoublyLinkedList {
    static class Node {
        int data;
        Node prev;   // link to the previous node
        Node next;   // link to the next node
        Node(int data) {
            this.data = data;
            this.prev = null;
            this.next = null;
        }
    }

    Node head;

    public void insertAtEnd(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
            return;
        }
        Node current = head;
        while (current.next != null) {
            current = current.next;
        }
        current.next = newNode;
        newNode.prev = current;   // the extra link a doubly list needs
    }

    public void displayForward() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " <-> ");
            current = current.next;
        }
        System.out.println("null");
    }

    public void displayBackward() {
        if (head == null) { System.out.println("null"); return; }
        Node current = head;
        while (current.next != null) {   // go to the last node first
            current = current.next;
        }
        while (current != null) {
            System.out.print(current.data + " <-> ");
            current = current.prev;      // walk backward using prev
        }
        System.out.println("null");
    }
}

Running insertAtEnd(10), insertAtEnd(20), and insertAtEnd(30) then printing both directions gives:

Console Output:
Forward:  10 <-> 20 <-> 30 <-> null
Backward: 30 <-> 20 <-> 10 <-> null

Circular Linked List

In a circular linked list, the last node points back to the head instead of null, so the chain forms a loop. This is common in assignments that cycle through items, like a task scheduler.

CircularLinkedList.java
class CircularLinkedList {
    static class Node {
        int data;
        Node next;
        Node(int data) { this.data = data; this.next = null; }
    }

    Node head;

    public void insertAtEnd(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
            newNode.next = head;   // points to itself, forming the circle
            return;
        }
        Node current = head;
        while (current.next != head) {   // stop at the last node
            current = current.next;
        }
        current.next = newNode;
        newNode.next = head;       // close the circle back to head
    }

    public void display() {
        if (head == null) { System.out.println("empty"); return; }
        Node current = head;
        do {
            System.out.print(current.data + " -> ");
            current = current.next;
        } while (current != head);     // stop when we loop back to head
        System.out.println("(back to head)");
    }
}
Console Output:
10 -> 20 -> 30 -> (back to head)

The key difference is the stopping condition. In a singly list you stop at null. In a circular list you stop when you arrive back at the head, so you must use a do-while loop or you will loop forever.

A Complete Worked Assignment: Build a Playlist With a Linked List

Real assignments usually store objects in the nodes, not just numbers. A very common style is "build a manager for a collection of items," such as a playlist, a contact book, or a task list. Here is a full worked example that builds a music playlist. Each node holds a Song object, and the list supports add, remove, find, total time, and print. This is the exact object-holding pattern most graded assignments expect.

PlaylistDemo.java
class Song {
    String title;
    int seconds;

    Song(String title, int seconds) {
        this.title = title;
        this.seconds = seconds;
    }

    public String toString() {
        return title + " (" + seconds + "s)";
    }
}

class Playlist {
    static class Node {
        Song song;
        Node next;
        Node(Song song) {
            this.song = song;
            this.next = null;
        }
    }

    Node head;

    public void addSong(Song song) {
        Node newNode = new Node(song);
        if (head == null) {
            head = newNode;
            return;
        }
        Node current = head;
        while (current.next != null) {
            current = current.next;
        }
        current.next = newNode;
    }

    public boolean removeSong(String title) {
        if (head == null) {
            return false;
        }
        if (head.song.title.equals(title)) {
            head = head.next;
            return true;
        }
        Node current = head;
        while (current.next != null && !current.next.song.title.equals(title)) {
            current = current.next;
        }
        if (current.next == null) {
            return false;
        }
        current.next = current.next.next;
        return true;
    }

    public Song findSong(String title) {
        Node current = head;
        while (current != null) {
            if (current.song.title.equals(title)) {
                return current.song;
            }
            current = current.next;
        }
        return null;
    }

    public int totalSeconds() {
        int total = 0;
        Node current = head;
        while (current != null) {
            total += current.song.seconds;
            current = current.next;
        }
        return total;
    }

    public void printPlaylist() {
        Node current = head;
        int track = 1;
        while (current != null) {
            System.out.println(track + ". " + current.song);
            current = current.next;
            track++;
        }
    }
}

public class PlaylistDemo {
    public static void main(String[] args) {
        Playlist playlist = new Playlist();
        playlist.addSong(new Song("Sunrise", 210));
        playlist.addSong(new Song("Ocean Drive", 185));
        playlist.addSong(new Song("Night Sky", 240));

        System.out.println("Your playlist:");
        playlist.printPlaylist();
        System.out.println("Total time: " + playlist.totalSeconds() + " seconds");

        System.out.println();
        System.out.println("Removing 'Ocean Drive'...");
        playlist.removeSong("Ocean Drive");
        playlist.printPlaylist();

        System.out.println();
        Song found = playlist.findSong("Night Sky");
        if (found != null) {
            System.out.println("Found: " + found);
        } else {
            System.out.println("Song not found.");
        }
    }
}
Console Output:
Your playlist:
1. Sunrise (210s)
2. Ocean Drive (185s)
3. Night Sky (240s)
Total time: 635 seconds

Removing 'Ocean Drive'...
1. Sunrise (210s)
2. Night Sky (240s)

Found: Night Sky (240s)

Notice how every method uses the same node-walking pattern from earlier, just applied to a Song object instead of an int. If your assignment uses Book, Student, Contact, or Task objects, swap the class and keep the structure. The pattern does not change.

One more tip for object-based lists: comparing objects often causes a bug. Use .equals() for String titles, as shown, not ==, because == compares memory addresses and not the actual text.

The Pointer Mistakes That Break Linked List Assignments

This is the part that separates a full-marks submission from a frustrating one, and it is where most students actually get stuck. Linked list bugs almost always come from mishandling the links. Here are the traps professors test on purpose.

  • Losing the rest of the list during insert: When inserting, always set the new node's next before you change the previous node's next. If you rewire in the wrong order, you cut off everything after the insertion point and lose it.
  • Forgetting the empty-list case: Many methods crash when head is null, because the code assumes at least one node exists. Every insert, delete, and search should check for an empty list first. This is a favorite grading test, since the rubric will run your method on an empty list.
  • Mishandling the head in delete: Deleting the head is special, because there is no node before it to rewire. If your delete only handles middle nodes, it will throw an error the moment the target is the head.
  • Running off the end: A loop condition like while (current.next != null) is safe, but while (current.next.data != target) without a null check will crash when it reaches the end. Always confirm current and current.next are not null before reading from them.
  • Infinite loops in circular lists: In a circular list, stopping at null never happens, because the last node points back to head. Use a do-while that stops when you return to head, or your program will loop forever.

Almost every one of these bugs shows up as a NullPointerException, which is the most common error students hit when building linked lists. If that error appears, our separate guide on how to fix a NullPointerException in your Java homework walks through reading the error and finding the exact line.

What Your Professor Grades in a Linked List Assignment

Understanding how these are scored helps you spend your time where the marks are. On a typical linked list assignment, the large majority of the points sit on the list methods themselves, meaning correct insert, delete, search, and swap logic, including the edge cases. A smaller share goes to the driver or main method that runs everything, and another small share to any supporting work like file reading or an ArrayList portion. Documentation, often required in JavaDoc format, is usually a pass-or-fail gate: skip it and you can lose marks across the whole assignment even if the code is perfect.

So the smart plan is to get your core list methods rock solid and fully tested first, since that is where most of the grade lives, then handle the driver, then write clean comments and documentation. Many students spend hours polishing the menu and output while leaving an edge case broken in the delete method, which is exactly backward from how the points are usually distributed.

How to Test Your Linked List Before Submitting

Do not submit after one lucky run. Test each method against the situations graders check. Insert into an empty list and confirm the head is set. Insert at the front, the end, and a middle position. Insert at a negative position and a position past the end, and confirm your code handles both without crashing. Delete the head, delete a middle node, delete the last node, and try to delete a value that is not there. Search for a value that exists and one that does not. Print the list after every operation and compare it to the sample output in your assignment, character by character, since graders often compare output directly.

Viva Questions on Linked Lists (With Sample Answers)

Many courses hold a viva or demo where you present your assignment and the professor asks questions to check that you wrote and understood the code. Here are the questions that come up most often, with short answers you can say in your own words.

  1. Why would you use a linked list instead of an array?
    A linked list can grow and shrink easily at runtime, and inserting or deleting at the front is fast because you only change a couple of links. An array has a fixed size and shifting elements for an insert or delete is slower. The trade-off is that a linked list cannot jump straight to the middle; you have to walk from the head.
  2. What does the head point to, and what happens if you lose it?
    The head points to the first node in the list. It is the only entry point, so if you accidentally reassign or lose the head, you lose access to the entire list, because there is no other way to reach the nodes.
  3. Walk me through what happens when you insert at a position.
    I walk from the head, counting nodes, and stop at the node just before the target position. Then I point my new node's next at the node that was there, and point the previous node's next at my new node. I also check for a negative position or a position past the end and handle those cases.
  4. Why does your delete method need to find the previous node?
    To remove a node, I have to connect the node before it directly to the node after it. That skips the target out of the chain. So I stop one node early, at the node before the target, so I can rewire its next link.
  5. What is the time complexity of searching your list?
    Searching is O(n), because in the worst case I walk every node from the head to the end. Unlike an array, I cannot jump to a specific index, so I check nodes one by one.
  6. How do you handle inserting into an empty list?
    When the list is empty, the head is null. In that case I just make the new node the head, since there is nothing to link it to yet. I check for this case at the top of every insert method.

Still have some confusions or you still feel stuck in your assignment, you can always ask our experts to help with your Java Linked list homework.  

FAQs (Questions Students Ask Us )

First, check whether your assignment wants you to build the list yourself or use Java’s built-in LinkedList. If you are building it, create a Node class with a data field and a next link, then a list class with a head field. From there, add your insert, delete, search, and display methods one at a time.

Walk from the head, counting nodes, and stop at the node just before the position you want. Point your new node’s next at the node currently there, then point the previous node’s next at your new node. Handle a position of 0 as a front insert, and check for positions that are negative or past the end.

Find the node just before the one you want to remove, then set its next to skip over the target and link to the node after it. Deleting the head is a special case, because there is no node before it, so you move the head to the next node instead.

A singly linked list gives each node one link, next, so you can only move forward. A doubly linked list gives each node two links, next and prev, so you can move both forward and backward. The doubly version uses more memory but makes some operations easier.

It usually means your code tried to use a link that was null, often by reading current.next when current was already at the end, or by forgetting the empty-list case. Add null checks before you follow a link, and always handle the empty list first.

Only if your assignment allows it. Some assignments require you to build the list yourself and give a zero for using java.util.LinkedList. Others want you to use the built-in class. Read your instructions carefully before you decide.

Leave a Comment

Your email address will not be published. Required fields are marked *