// 定義鏈表的節(jié)點(diǎn)類
class Node {
int data; // 節(jié)點(diǎn)中的數(shù)據(jù)
Node next; // 指向下一個(gè)節(jié)點(diǎn)的引用
public Node(int data) {
this.data = data;
this.next = null; // 初始時(shí)下一個(gè)節(jié)點(diǎn)為null
}
}
// 定義單向鏈表類
class LinkedList {
private Node head; // 鏈表的頭節(jié)點(diǎn)
// 初始化空鏈表
public LinkedList() {
this.head = null;
}
// 添加節(jié)點(diǎn)到鏈表末尾
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode; // 如果鏈表為空氨鹏,直接讓頭節(jié)點(diǎn)指向新節(jié)點(diǎn)
} else {
Node current = head;
while (current.next != null) { // 找到最后一個(gè)節(jié)點(diǎn)
current = current.next;
}
current.next = newNode; // 將新節(jié)點(diǎn)添加到最后
}
}
// 打印鏈表中的所有元素
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null"); // 最后打印null表示鏈表結(jié)束
}
}
// 測試鏈表
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.printList(); // 輸出: 1 -> 2 -> 3 -> null
}
}