对于熟悉Java的开发人员来说,显而易见的解决方案是使用java.util中已经提供的LinkedList类。说,但是,由于某种原因,您想进行自己的实现。这是一个链接列表的快速示例,该链接列表在列表的开头插入新链接,从列表的开头删除并循环浏览列表以打印其中包含的链接。对此实现的增强包括使其成为双向链接列表,添加从中间或结尾插入和删除的方法以及添加get和sort方法。
注意:在示例中,Link对象实际上并不包含另一个Link对象 -nextLink实际上只是对另一个链接的引用。
class Link {
public int data1;
public double data2;
public Link nextLink;
//Link constructor
public Link(int d1, double d2) {
data1 = d1;
data2 = d2;
}
//Print Link data
public void printLink() {
System.out.print("{" + data1 + ", " + data2 + "} ");
}
}
class LinkList {
private Link first;
//LinkList constructor
public LinkList() {
first = null;
}
//Returns true if list is empty
public boolean isEmpty() {
return first == null;
}
//Inserts a new Link at the first of the list
public void insert(int d1, double d2) {
Link link = new Link(d1, d2);
link.nextLink = first;
first = link;
}
//Deletes the link at the first of the list
public Link delete() {
Link temp = first;
if(first == null){
return null;
//throw new NoSuchElementException(); // this is the better way.
}
first = first.nextLink;
return temp;
}
//Prints list data
public void printList() {
Link currentLink = first;
System.out.print("List: ");
while(currentLink != null) {
currentLink.printLink();
currentLink = currentLink.nextLink;
}
System.out.println("");
}
}
class LinkListTest {
public static void main(String[] args) {
LinkList list = new LinkList();
list.insert(1, 1.01);
list.insert(2, 2.02);
list.insert(3, 3.03);
list.insert(4, 4.04);
list.insert(5, 5.05);
list.printList();
while(!list.isEmpty()) {
Link deletedLink = list.delete();
System.out.print("deleted: ");
deletedLink.printLink();
System.out.println("");
}
list.printList();
}
}