private static class Node<E> {
E data;
Node<E> next;
Node(E e) { this.data = e; this.next = null; }
}
內部靜態類 Node 封裝資料與指標,泛型 E 支援任意類型元素。
head:頭節點(哨兵或首元素)last:尾節點,支援 O(1) 尾插length:節點計數other:遍歷用暫存指標public NodeList() { this.head = new Node<>(null); }
public NodeList(E data) {
this.head = new Node<>(data);
this.last = head;
length++;
}
add(E)public void add(E data) {
if (isEmpty()) {
head = new Node<>(data);
last = head;
} else {
Node<E> n = new Node<>(data);
last.next = n;
last = n;
}
length++;
}
get(int)public E get(int index) {
if (index < 0 || index >= length)
throw new IndexOutOfBoundsException("索引越界:" + index);
Node<E> cur = head;
for (int i = 0; i < index; i++) cur = cur.next;
return cur.data;
}
add(E target, E insert)public boolean add(E target, E insert) {
Node<E> cur = head;
while (cur != null) {
if (cur.data.equals(target)) {
Node<E> n = new Node<>(insert);
n.next = cur.next;
cur.next = n;
length++;
return true;
}
cur = cur.next;
}
return false;
}
remove(E)public boolean remove(E data) {
Node<E> cur = head, prev = head;
while (cur != null) {
if (cur.data.equals(data)) {
prev.next = cur.next;
if (cur == last) last = prev; // 維護尾指標
length--;
return true;
}
prev = cur;
cur = cur.next;
}
return false;
}
| 方法 | 功能 | 時間複雜度 |
|---|---|---|
contains(E) | 判斷是否包含元素 | O(n) |
set(E old, E new) | 首次出現的 old 替換為 new | O(n) |
isEmpty() | 鏈表是否為空 | O(1) |
clear() | 清空鏈表 | O(1) |
printLink() | 列印所有元素 | O(n) |
public class NodeList<E> {
private static class Node<E> { /* 略 */ }
private Node<E> head, last, other;
private int length = 0;
/* 以上所有方法完整實作 */
}
lastNode<E> 實為 Node,無法 new E[],僅影響陣列建構