java实现单链表的基本操作
时间: 2023-09-11 08:07:21 浏览: 80
单链表是一种常见的数据结构,它由一个节点序列组成,每个节点包含了一个数据元素和一个指向下一个节点的指针。下面是Java实现单链表的基本操作:
1. 定义单链表节点类
```
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
```
2. 定义单链表类,包含插入、删除、查找等基本操作
```
class LinkedList {
ListNode head;
public void insert(int val) {
ListNode node = new ListNode(val);
if (head == null) {
head = node;
} else {
ListNode curr = head;
while (curr.next != null) {
curr = curr.next;
}
curr.next = node;
}
}
public void delete(int val) {
if (head == null) {
return;
}
if (head.val == val) {
head = head.next;
return;
}
ListNode prev = head;
ListNode curr = head.next;
while (curr != null && curr.val != val) {
prev = curr;
curr = curr.next;
}
if (curr != null) {
prev.next = curr.next;
}
}
public ListNode search(int val) {
ListNode curr = head;
while (curr != null && curr.val != val) {
curr = curr.next;
}
return curr;
}
}
```
3. 测试单链表
```
public class TestLinkedList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insert(1);
list.insert(2);
list.insert(3);
list.delete(2);
ListNode node = list.search(3);
System.out.println(node.val);
}
}
```
阅读全文