Java中實現鏈表的方法是使用Node類來定義鏈表節點,然后使用LinkedList類來實現鏈表的各種操作。
具體步驟如下:
class Node {
int data;
Node next;
}
class LinkedList {
Node head;
// 插入節點
public void insert(int data) {
Node newNode = new Node();
newNode.data = data;
newNode.next = null;
if (head == null) {
head = newNode;
} else {
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = newNode;
}
}
// 刪除節點
public void delete(int data) {
if (head == null) {
return;
}
if (head.data == data) {
head = head.next;
return;
}
Node curr = head;
Node prev = null;
while (curr != null && curr.data != data) {
prev = curr;
curr = curr.next;
}
if (curr != null) {
prev.next = curr.next;
}
}
// 查找節點
public Node search(int data) {
Node curr = head;
while (curr != null && curr.data != data) {
curr = curr.next;
}
return curr;
}
// 遍歷鏈表
public void printList() {
Node curr = head;
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insert(5);
list.insert(10);
list.insert(15);
list.printList(); // 輸出:5 10 15
list.delete(10);
list.printList(); // 輸出:5 15
Node node = list.search(15);
if (node != null) {
System.out.println("找到了節點:" + node.data);
} else {
System.out.println("沒有找到節點");
}
}
}
以上代碼實現了一個簡單的鏈表,包含插入、刪除和查找等操作,可以根據需要進行擴展。