Make linked list in Java
If you’re actually building a real production system, then yes, you’d typically just use the stuff in the standard library if what you need is available there. That said, don’t think of this as a pointless exercise. It’s good to understand how things work, and understanding linked lists is an important step towards understanding more complex data structures, many of which don’t exist in the standard libraries. There are some differences between the way you’re creating a linked list and the way the Java collections API does it. The Collections API is trying to adhere to a more complicated interface. Your LinkedList will always have at least one element. With this kind of setup you’d use null for when you need an empty list. Think of “next” as being “the rest of the list”. In fact many people would call it tail instead of “next”. Here’s a diagram of a singly LinkedList: Another must read: What’s the best way to make a linkedlist in Java from scratch?Well, here is a simplest implementation of LinkedList Class in Java.
Few things:Here we are initialize Node only while adding 1st element.
Result:
Enhancements to this implementation include making it a double-linked list, adding methods to insert and delete from the middle or end, and by adding get and sort methods as well. Referenced answer from Stack Overflow by Laurence Gonsalves. You may be interested in list of all Java Tutorials. If you liked this article, then please share it on social media. Still have any questions about an article, leave us a comment. |