在Java中,鏈表的實現通常是通過創建一個節點類(Node)和一個鏈表類(LinkedList)。節點類包含一個數據域和一個指向下一個節點的引用。鏈表類包含一個頭節點引用,用于存儲鏈表的第一個元素。以下是一個簡單的單向鏈表實現:
public class Node<T> {
private T data;
private Node<T> next;
public Node(T data) {
this.data = data;
this.next = null;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
}
public class LinkedList<T> {
private Node<T> head;
public LinkedList() {
this.head = null;
}
// 添加元素到鏈表頭部
public void addFirst(T data) {
Node<T> newNode = new Node<>(data);
newNode.setNext(head);
head = newNode;
}
// 添加元素到鏈表尾部
public void addLast(T data) {
Node<T> newNode = new Node<>(data);
if (head == null) {
head = newNode;
} else {
Node<T> current = head;
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(newNode);
}
}
// 從鏈表中刪除第一個元素
public T removeFirst() {
if (head == null) {
throw new IllegalStateException("List is empty");
}
T data = head.getData();
head = head.getNext();
return data;
}
// 遍歷鏈表并打印元素
public void traverse() {
Node<T> current = head;
while (current != null) {
System.out.print(current.getData() + " -> ");
current = current.getNext();
}
System.out.println("null");
}
}
現在你可以創建一個鏈表對象并使用這些方法來操作它:
public class Main {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.addFirst(1);
list.addLast(2);
list.addFirst(0);
list.traverse(); // 輸出: 0 -> 1 -> 2 -> null
System.out.println(list.removeFirst()); // 輸出: 0
list.traverse(); // 輸出: 1 -> 2 -> null
}
}
這個實現僅包含單向鏈表的基本操作。你可以根據需要擴展這個實現,例如添加雙向鏈表支持、鏈表反轉等。