insert、remove、retrieve、search方法代码,未测试:
public void insert(E data) {
if (data == null) {
return;
}
NodedummyHead = new Node (null);
dummyHead.next = head;
insert(dummyHead, data);
head = dummyHead.next;
dummyHead.next = null;
}
public void insert(Nodepre, E data) {
Nodecur = pre.next;
if (cur == null || data.compareTo(cur.data) <= 0) {
Nodenode = new Node (data);
node.next = cur.next;
cur.next = node;
} else {
insert(pre.next, data);
}
}
public void remove(E data) {
if (head == null) {
return;
}
NodedummyHead = new Node (data);
dummyHead.next = head;
remove(dummyHead, data);
head = dummyHead.next;
dummyHead.next = null;
}
private void remove(Nodepre, E data) {
if (pre == null || pre.next == null) {
return;
}
Nodecur = pre.next;
if (cur.data == data || cur.data != null && cur.data.equals(data)) {
pre.next = cur.next;
cur.next = null;
} else {
remove(pre.next, data);
}
}
public E retrieve(int index) {
return retrieve(head, index);
}
private E retrieve(Nodehead, int index) {
if (head == null || index < 0) {
return null;
}
if (index == 0) {
return head.data;
}
return retrieve(head.next, index - 1);
}
public boolean search(E data) {
return search(head, data);
}
private boolean search(Nodehead, E data) {
if (head == null) {
return false;
}
if (head.data == data || head.data != null && head.data.equals(data)) {
return true;
}
return search(head.next, data);
}
}