Java中實現(xiàn)鏈表的方法是使用Node類來定義鏈表節(jié)點,然后使用LinkedList類來實現(xiàn)鏈表的各種操作。
具體步驟如下:
class Node {
int data;
Node next;
}
class LinkedList {
Node head;
// 插入節(jié)點
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;
}
}
// 刪除節(jié)點
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;
}
}
// 查找節(jié)點
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("找到了節(jié)點:" + node.data);
} else {
System.out.println("沒有找到節(jié)點");
}
}
}
以上代碼實現(xiàn)了一個簡單的鏈表,包含插入、刪除和查找等操作,可以根據(jù)需要進行擴展。