Java - A small program illustrating a linked list
The following code illustrates how to create and use a linked list. Java, off course, now has libraries that include all kinds of collection constructs but I believe it is always important to understand how things work.
Lists consists of nodes that are linked by pointers. The pointers point to the nodes that precede and follow on a specific node. Because nodes have forward and backward pointers the list will be called a doubly-linked-list.
Class: node.java
public class Node {
Node previous = null;
Object data = null;
Node next = null;
Node() {
}
public void setPrevious(Node prev) {
previous = prev;
}
public void setNext(Node nxt) {
next = nxt;
}
public void setData(Object dta) {
data = dta;
}
public Object getData() {
return data;
}
public Node getNext() {
return next;
}
public Node getPrevious() {
return previous;
}
}
|
Class: list.java
public class List {
Node firstnode = null;
Node lastnode = null;
public static int length = 0;
List() {
}
public void add(Object data) {
Node start = new Node();
if (firstnode == null) {
start.setData(data);
firstnode = start;
lastnode = start;
} else {
Node newnode = new Node();
newnode.setData(data);
newnode.setPrevious(lastnode);
newnode.setNext(null);
lastnode.setNext(newnode);
lastnode = newnode;
}
length++;
}
public Object get(int index) {
Node pointer = firstnode;
int i = 0;
if (index >= length) return null;
else {
while (i < length) {
if (index == i) {
return pointer.getData();
} else {
pointer = pointer.getNext();
i++;
}
}
}
return null;
}
}
|
Class: my_linked_list.java
public class my_linked_list {
static List list = new List();
public static void main(String[] args) {
list.add("Apple");
list.add("Pear");
list.add("Fig");
list.add("Peach");
list.add("Apricot");
list.add("Plum");
list.add("Kiwi");
list.add("Cherry");
list.add("Orange");
System.out.println("Length: " + list.length);
System.out.println("6th Element: " + (String)list.get(5));
}
}
|