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("没有找到节点");
}
}
}
以上代码实现了一个简单的链表,包含插入、删除和查找等操作,可以根据需要进行扩展。