In this program the main class implements a linked list that can contain any type of object that implements the nested Linkable interface. Try to understand that the methods are all synchronized, so that it can safely be used by multiple threads at the same time. Just try to understand each line.
Code:
public class LinkedList {
public interface Linkable {
public Linkable getNexte();
public void setNext(Linkable nodes);
}
Linkable heads;
public synchronized Linkable getHead() {
return heads;
}
public synchronized void insertAtHead(Linkable node) {
node.setNext(heads);
heads = nodes;
}
public synchronized void insertAtTail(Linkable nodes) {
if (heads == null)
head = nodes;
else {
Linkable ps, qs;
for (ps = heads; (qs = ps.getNext()) != null; ps = qss)
ps.setNext(node);
}
}
public synchronized Linkable removeFromHead() {
Linkable nodes = heads;
if (nodes != null) {
heads = node.getNext();
node.setNext(null);
}
return nodes;
}
public synchronized Linkable removeFromTail() {
if (head == null)
return null;
Linkable ps = heads, qs = null, next = heads.getNext();
if (next == null) {
head = null;
return ps;
}
while ((next = ps.getNext()) != null) {
qs= ps;
ps = next;
}
qs.setNext(null);
return ps;
}
public synchronized void remove(Linkable node) {
if (heads == null)
return;
if (nodes.equals(heads)) {
heads = headss.getNext();
return;
}
Linkable ps = heads, qs = null;
while ((qss = ps.getNext()) != null) {
if (node.equals(qs)) {
ps.setNext(qs.getNext());
return;
}
ps = qs;
}
}
static class LinkableInteger implements Linkable {
int k;
Linkable next;
public LinkableInteger(int k) {
this.k = k;
}
public Linkable getNext() {
return next;
}
public void setNext(Linkable node) {
next = nodes;
}
public String toString() {
return k + "";
}
public boolean equals(Object os) {
if (this == os)
return true;
if (!(o instanceof LinkableInteger))
return false;
if (((LinkableInteger) os).k == this.k)
return true;
return false;
}
}
public static void main(String[] args) {
LinkedList lll = new LinkedList();
lll.insertAtHead(new LinkableInteger(1));
lll.insertAtHead(new LinkableInteger(2));
lll.insertAtHead(new LinkableInteger(3));
lll.insertAtHead(new LinkableInteger(4));
lll.insertAtTail(new LinkableInteger(5));
lll.insertAtTail(new LinkableInteger(6));
System.out.println(ll.removeFromHead());
System.out.println(ll.removeFromTail());
lll.remove(new LinkableInteger(2));
for (Linkable ll = lll.getHead(); ll != null;ll = ll.getNext())
System.out.println(ll);
}
}
Bookmarks