链表好久不用了,到现在只用数组和哈希表。
[code="java"]
package pkg;
public class Node implements Comparable {
private Integer value;
private Node next;
public Node(){
}
public Node(Integer value, Node next) {
this.value = value;
this.next = next;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public int compareTo(Object o) {
Node another = (Node) o;
return value.compareTo(another.getValue());
}
}
[/code]
[code="java"]
package pkg;
public class IntegerList {
public IntegerList() {
first = null;
size = 0;
}
public void add(Node node) {
if(isEmpty()) {
first = node;
size = 1;
} else {
privateAddNode(node);
size++;
}
}
public boolean isEmpty() {
return first == null;
}
public Node getFirst() {
return first;
}
public int size() {
return size;
}
private void privateAddNode(Node node) {
Node currentNode = null, priorNode = null;
if(first.compareTo(node) >= 0) {
node.setNext(first);
first = node;
return;
}
priorNode = first;
currentNode = first.getNext();
while(currentNode != null) {
if(currentNode.compareTo(node) >= 0) {
priorNode.setNext(node);
node.setNext(currentNode);
return;
}
priorNode = currentNode;
currentNode = currentNode.getNext();
}
priorNode.setNext(node);
node.setNext(null);
}
private Node first;
private int size;
}
[/code]
[code="java"]
package pkg;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
IntegerList list1 = new IntegerList();
list1.add(new Node(Integer.valueOf(4), null));
list1.add(new Node(Integer.valueOf(5), null));
list1.add(new Node(Integer.valueOf(1), null));
list1.add(new Node(Integer.valueOf(3), null));
IntegerList list2 = new IntegerList();
list2.add(new Node(Integer.valueOf(-3), null));
list2.add(new Node(Integer.valueOf(5), null));
list2.add(new Node(Integer.valueOf(100), null));
list2.add(new Node(Integer.valueOf(100), null));
list2.add(new Node(Integer.valueOf(-3), null));
Node node = list2.getFirst();
while(node != null) {
int value = node.getValue().intValue();
list1.add( new Node(Integer.valueOf(value), null) );
node = node.getNext();
}
node = list1.getFirst();
while(node != null) {
System.out.println(node.getValue());
node = node.getNext();
}
}
}
[/code]
控制台打印:
-3
-3
1
3
4
5
5
100
100