java单链表例题完整代码
时间: 2024-11-03 15:08:18 浏览: 20
在Java中,我们可以创建一个简单的单链表节点类`Node`和一个链表类`LinkedList`来进行操作。这里是一个基本的例子,包含节点的定义和链表的一些基本功能,如添加元素、删除元素等:
```java
// 定义单链表节点
class Node {
int data;
Node next;
// 构造函数
public Node(int value) {
data = value;
next = null;
}
}
// 单链表类
public class LinkedList {
private Node head; // 链表头节点
// 添加元素到链表尾部
public void add(int value) {
if (head == null) {
head = new Node(value);
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = new Node(value);
}
}
// 删除指定值的节点(如果存在)
public void remove(int value) {
if (head == null) return;
if (head.data == value) {
head = head.next;
return;
}
Node previous = head;
Node current = head.next;
while (current != null && current.data != value) {
previous = current;
current = current.next;
}
if (current != null) {
previous.next = current.next;
}
}
// 打印链表
public void printList() {
Node node = head;
while (node != null) {
System.out.print(node.data + " -> ");
node = node.next;
}
System.out.println("null");
}
}
```
阅读全文