java手写链表便利
时间: 2024-06-12 22:03:09 浏览: 101
java链表
在Java中,手写链表(也称为单链表)是一种基础数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的引用。创建和操作链表的便利之处在于它的动态性和灵活性,可以在运行时添加或删除元素,而不需要像数组那样预先分配固定大小。
下面是一个简单的Java链表节点和链表类的例子:
```java
// 链表节点定义
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
// 链表类定义
public class LinkedList {
private Node head; // 头节点
// 插入节点方法
public void insert(int value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
// 查找节点方法
public boolean contains(int value) {
Node current = head;
while (current != null) {
if (current.data == value) {
return true;
}
current = current.next;
}
return false;
}
// 删除节点方法
public void remove(int value) {
if (head == null) {
return;
}
if (head.data == value) {
head = head.next;
return;
}
Node current = head;
while (current.next != null && current.next.data != value) {
current = current.next;
}
if (current.next != null) {
current.next = current.next.next;
}
}
// 显示链表元素(仅做演示,实际应用中可能有更优雅的方法)
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
}
```
阅读全文