I see that this causes a cycle

 ptr.nextNode = temp;
 temp.nextNode = ptr.nextNode;

as temp.nextNode points to itself.

U need to interchange these lines

Answer from Aditya K on Stack Overflow
๐ŸŒ
CodeSpeedy
codespeedy.com โ€บ home โ€บ how to use linked list in java without using collection class
How to use Linked List In Java Without Using Collection Class
September 6, 2019 - You can assume you are given access to the head node of the Linked List, else ยท //Itโ€™s always good to preserve the head node and not use it for any operations. Unless you are sorting or reversing a linked list in which case you need to update the head node.
๐ŸŒ
YouTube
youtube.com โ€บ coding macha
Basic LinkedList Code in Java Without Collections - YouTube
Hi machaa, In this Video I'll be discussing - on Basic Linked List Program in Java without using CollectionsThis will be Useful for questions of type - Autom...
Published: October 27, 2020
Views: 2K
Discussions

Linked list without using collections in Java - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... This is my Java program to insert an element in a linked list. More on stackoverflow.com
๐ŸŒ stackoverflow.com
December 24, 2016
How to create a linked list in java without importing linked lists - Stack Overflow
i am a CS student in college and i am having trouble with this project where i am supoosed to create a linked list using nodes without importing linked lists, as well as doing a some methods with the More on stackoverflow.com
๐ŸŒ stackoverflow.com
Creating linked lists in java without using in-built methods/importing util - Stack Overflow
Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. The question is to create a linked list that creates nodes and links them and should have the following methods. ... Insert before and after... I've managed to do the bit below but I can't seem to get what's wrong with the code. Piece of the error reads " LinkedList.java ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
September 27, 2015
Singly linked list implementation in Java without help of java.util.linkedlist - Code Review Stack Exchange
I am learning Java and as a first exercise I tried to implement singly linked list without the help of java.util. I tested my program for basic operations and it seems to work fine. But I still wan... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
January 10, 2017
๐ŸŒ
Coolcheatsheet
coolcheatsheet.com โ€บ question โ€บ how-to-implement-linked-list-in-java-without-using-collection-framework
How To Implement Linked List In Java Without Using Collection Framework - CoolCheatSheet.com
public class linkedlist { public static class Node //We are defining a node here { int data; //data of node here Node next; //next refers to the address of the next node } public static void main(String args[]) { Node newnode1=new Node(); //here we are making objects of class Node Node newnode2=new Node(); //basically these are nodes of first linkedlist Node newnode3=new Node(); Node newnode4=new Node(); newnode1.data=1; newnode2.data=2; newnode3.data=3; newnode4.data=4; newnode1.next=newnode2; //here we are linking the previous node to the next node of the list newnode2.next=newnode3; newnode
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 66606949 โ€บ how-to-create-a-linked-list-in-java-without-importing-linked-lists
How to create a linked list in java without importing linked lists - Stack Overflow
i am a CS student in college and i am having trouble with this project where i am supoosed to create a linked list using nodes without importing linked lists, as well as doing a some methods with the
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_linkedlist.asp
Java LinkedList
LinkedList stores elements as linked nodes, making inserts and removals fast.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 398011 โ€บ java โ€บ LINK-LIST-JAVA-COLLECTION-FRAMEWORK
LINK LIST IN JAVA WITHOUT COLLECTION FRAMEWORK (Beginning Java forum at Coderanch)
December 13, 2004 - If so, start by making a list of the fundamental operations a linked list type should have, and then create a class with methods to represent those operations. ... Below is the program for creating and printing linkedlist without using java collection framework [JAM -- edited to have [CODE] and [/CODE] tags] [ December 14, 2004: Message edited by: Joel McNary ]
Find elsewhere
Top answer
1 of 2
4

I've only glanced at your code, but two things stood out.

Immutable

In HeadNode you have a comment:

// immutable class representing head node of linked list

Either immutable doesn't mean what you think it does, or this comment is confused. Immutable classes don't change after they've been constructed. They typically have final members so that they can't be assigned to. You HeadNode class provides bother a getter and a setter for its only field nextNode. This isn't an immutable class.

Testing

Rather than rolling your own tests in main, consider looking into a testing framework like JUnit. It allows you to encapsulate tests for different functionality in a more expressive way, so that you can clearly tell from the test runs what is failing if you introduce bugs.

A few afterthoughts to add to @Jonas' answer.

Node

At the moment you have a distinction between nodes that have data (Node) and nodes that don't have data (HeadNode). Does it really make sense to have a Node that doesn't have a dataitem associated with it? Looking at your code, the answer is probably not, the first thing you do after creating a new Node is to call setDataItems. With that in mind, it would be better to add a constructor to your Node class that takes in a data item, rather than requiring the client to call a member function immediately after construction.

Efficiency

As @Janos pointed out, some of your methods are not very efficient. The one that most struck me was your searchKey method. It relies on your dataAtNodeIndex method which in turn relies on nodeAtIndex. Since your nodeAtIndex always starts from head, you end up searching the list over and over again from the start, going one item further each time until you find they key you're looking for.

Error Checking

Some of your methods can fail, but don't have a method for telling the client. For example, insertNodeAtIndex and deleteNodeAtIndex both return void. They also have ways that they can fail to deliver on their promises and fail silently. If a client calls insertNodeAtIndex(5) when the list only has 3 items, then you have a few options. At the moment, you effectively ignore the request (the client has no way to know that the item hasn't been added to the list). It would be better to at the item to the tail of the list (this fulfils the insert promise). However, it would be better still to throw an exception to indicate to the client that they've made an invalid request and that the item hasn't been inserted into the list.

2 of 2
3

Adding to forsvarir's Answer:

Code Style

Whitespace

Try to use whitespace more consistently. Correct indentation can make code much more readable. Sometimes you put a space before the opening braces after a method definition or around operators (=, +, etc.), sometimes you don't. I won't tell you to put spaces there or to leave them out, that's mostly personal preference or convention (I prefer putting spaces), but when you decide to do one or the other, stick to it.

Parameter Names

All your method parameter's names start with an underscore, which doesn't look particularly nice. If you're already using the this-Keyword to access your object's properties, there is no need to give the parameter a different name than your attributes, since prefixing the name with this. will already tell Java to use the object's property instead of the parameter.

Method Names

insertNode gives the impression it inserts a Node at a freely specified point in the list. Actually, it does neither: it adds the element at the front of the list (making it the new head) and it (from the user's perspective) doesn't add a Node, but a DataItems element to the list. Maybe prependElement would be better suited here. Same goes for deleteNode and generally any method with "node" in its name - of course it is a linked list and thus uses nodes underneath, but that detail should probably be hidden from the user.

Class Names

DataItems only represents a single item, it would be better to not use the pllural form for its name.

Architecture

Unnecessary HeadNode

Your LinkedList stores a reference to a HeadNode. HeadNodes only purpose seems to be to hold a reference to a Node, so why not remove the HeadNode-class altogether and directly use a Node in your LinkedList?

Coupling

Your LinkedList and Node implementations directly use the DataItems class for storing data. The whole linked list-scenario seems like a perfect example for learning to use Java's Generics: That way you can not only use your LinkedList to store DataItems, but any object. You can modify DataItems in the same way to use any type as key or value. See Generic Types for more information on that topic.

If you implemented your list like this, you could also consider implementing Java's List<E> interface to make it completely interchangable with other List-type in Java. While that violates not using the java.util package, it offers quite a range of new things to learn, while trying to implement all methods required by the interface.

Of course, when you use Generics instead of DataItems directly, your searchKey method cannot be implemented as it is now. Instead, you'd need a method (let's call it find), which takes a predicate (i.e. a function taking the datatype stored in your list and returning a true if the item matches whatever you're looking for) as its parameter.

Implementation

Insertion and Deletion

Your insertNode and deleteNode methods both are called when executing insertNodeAtIndex(0, data) and deleteNodeAtIndex(0), respectively. I recommend doing it the other way around, i.e. calling deleteNodeAtIndex(0) from deleteNode in order to keep the insertion/deletion code neatly in a single method instead of splitting it over two separate methods. Also, I would move the method definitions closer together, so you don't have to search too much to find the related method. Always try to keep methods with similar responsibilities closely together in the source file.

Reversing the List

Your implementation of reverseLinkedList is pretty inefficient. For each node in your list, it calls the nodeAtIndex method, which itself iterates over the whole list, causing it to fall in the \$O(nยฒ)\$ group of algorithms. Reversing the list could be done in \$O(n)\$ when using a Stack or recursion.

Calculating the List's Size

This implementation, too, is in \$O(nยฒ)\$ while it could be done in \$O(n)\$. Instead of always calling nodeAtIndex, just put the first node in a variable and in the while loop, check if the element is null, incrementing count and replacing the node with the next node.

๐ŸŒ
Javatpoint
javatpoint.com โ€บ java-program-to-create-and-display-a-singly-linked-list
Java Program to create and display a singly linked list - Javatpoint
Java Program to create and display a singly linked list - Java Program to create and display a singly linked list on fibonacci, factorial, prime, armstrong, swap, reverse, search, sort, stack, queue, linkedlist, tree, graph, pattern, string etc.
๐ŸŒ
Software Testing Help
softwaretestinghelp.com โ€บ home โ€บ java โ€บ linked list in java โ€“ linked list implementation & java examples
Linked List In Java โ€“ Linked List Implementation & Java Examples
April 1, 2025 - For applications that have mostly read-only data, ArrayList or similar collections can be used. ... Answer: A ListNode is a basic class associated with a linked list in Java and represents information associated with a single element or a node.
Top answer
1 of 1
2

It's a tad ridiculous to talk about 'efficiency' for such an incredibly inefficient data storage mechanism. Note that linked lists are far less efficient than basic analysis of algorithmic complexity (O(n) analysis) suggests. Things nearby in memory are faster because CPUs can't operate on memory directly, they only operate on entire pages in cache. If a page isn't in cache, it needs to be fetched, and that takes 500 or more cycles - and none of this is covered by algorithmic complexity.

With those little tracker objects (Those Link objects), there's way more 'traffic' going on and more cache misses. Hence - if you want efficiency, just use ArrayList, or ArrayDeque, or any of many other data types that are more suitable to the job (the point is more or less: For just about every job imaginable, LinkedList is not the best answer. There is no one solution that beats LinkedList for all imaginable situations, but LinkedList is nevertheless effectively never the right answer).

To get to your question: Well, if you still care about efficiency, I suggest you read the Quicksort wikipedia page.

It doesn't just explain this algorithm, it also has some useful pictures to show how it works. Quicksort is algorithmically perfect (It's O(nlogn), and we have 'proof' that sorting a list cannot be any faster than that). There are a few takes on this that can be faster in practice, but that's a few bridges too far if you haven't even learned Collections yet, so let's try not to go overboard.

If you want to phone this homework in, you could consider searching the web for quicksort singly linked list java - but you wouldn't learn very much if you did that :P

๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ examples โ€บ linkedlist-implementation
Java Program to Implement LinkedList
import java.util.LinkedList; class Main { public static void main(String[] args){ // create a linked list using the LinkedList class LinkedList<String> animals = new LinkedList<>(); // Add elements to LinkedList animals.add("Dog"); // add element at the beginning of linked list animals.addFirst("Cat"); // add element at the end of linked list animals.addLast("Horse"); System.out.println("LinkedList: " + animals); // access first element System.out.println("First Element: " + animals.getFirst()); // access last element System.out.println("Last Element: " + animals.getLast()); } }
๐ŸŒ
NareshIT
nareshit.com โ€บ blogs โ€บ linked-lists-in-java-working-use-cases-explained
Linked Lists in Java: Working & Use Cases Explained | NareshIT
Linked Lists are better when insertions/deletions are frequent. ArrayLists are better for random access and iteration. Searching requires traversal from the head/node one-by-one, making it O(n). There is no direct index-based access. Yes. Java's built-in LinkedList uses a doubly linked list implementation for bidirectional traversal.
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 8 โ€บ docs โ€บ api โ€บ java โ€บ util โ€บ LinkedList.html
LinkedList (Java Platform SE 8 )
July 21, 2026 - Returns a shallow copy of this LinkedList. (The elements themselves are not cloned.) ... Returns an array containing all of the elements in this list in proper sequence (from first to last element). The returned array will be "safe" in that no references to it are maintained by this list. (In other words, this method must allocate a new array). The caller is thus free to modify the returned array. This method acts as bridge between array-based and collection-based APIs.
๐ŸŒ
Medium
medium.com โ€บ quick-code โ€บ java-tips-a-homemade-linked-list-9adae0906332
Java Tips โ€” A homemade linked list | by Marco Domenico Marino | Quick Code | Medium
September 22, 2019 - Full list: in this case is needed to override the value of the first variable with the pointer to the next node of the same first node. The old first node will remain without reference and will be caught by the garbage collector ... One-element list: the linked list needs to be iterate, if the current node has a null pointer for the next node is needed to set to null the first and the last node because the list is now empty.
๐ŸŒ
Hackajob
hackajob.com โ€บ talent โ€บ blog โ€บ implementing-linked-lists-in-java
How to Implement Linked Lists in Java
November 5, 2025 - This means that the list has just one node and you can set the head as null. If that is also not the case, you will retrieve the value from the next field of the first node and set it as the new head. This will remove the link to the current first node and will be cleared up by the garbage collector in Java...
๐ŸŒ
Medium
medium.com โ€บ @vishwarajsali โ€บ implementation-of-singly-linked-list-in-java-e74c2c88ea44
Implementation of Singly Linked List in Java | by Vishwaraj Sali | Medium
January 6, 2024 - The implementation of the LinkedList ... that point from one node to the next. The solution includes an inner class, Node, to define the structure of each node in the linked list....