What's the best way to make a linked list in Java?
This question is related to
java
data-structures
linked-list
Its much better to use java.util.LinkedList, because it's probably much more optimized, than the one that you will write.
Use java.util.LinkedList. Like this:
list = new java.util.LinkedList()
//slightly improved code without using collection framework
package com.test;
public class TestClass {
private static Link last;
private static Link first;
public static void main(String[] args) {
//Inserting
for(int i=0;i<5;i++){
Link.insert(i+5);
}
Link.printList();
//Deleting
Link.deletefromFirst();
Link.printList();
}
protected static class Link {
private int data;
private Link nextlink;
public Link(int d1) {
this.data = d1;
}
public static void insert(int d1) {
Link a = new Link(d1);
a.nextlink = null;
if (first != null) {
last.nextlink = a;
last = a;
} else {
first = a;
last = a;
}
System.out.println("Inserted -:"+d1);
}
public static void deletefromFirst() {
if(null!=first)
{
System.out.println("Deleting -:"+first.data);
first = first.nextlink;
}
else{
System.out.println("No elements in Linked List");
}
}
public static void printList() {
System.out.println("Elements in the list are");
System.out.println("-------------------------");
Link temp = first;
while (temp != null) {
System.out.println(temp.data);
temp = temp.nextlink;
}
}
}
}
Java has a LinkedList implementation, that you might wanna check out. You can download the JDK and it's sources at java.sun.com.
The above linked list display in opposite direction. I think the correct implementation of insert method should be
public void insert(int d1, double d2) {
Link link = new Link(d1, d2);
if(first==null){
link.nextLink = null;
first = link;
last=link;
}
else{
last.nextLink=link;
link.nextLink=null;
last=link;
}
}
Source: Stackoverflow.com