单向链表及其java实现
时间: 2024-01-07 18:00:57 浏览: 103
单向链表是一种常见的数据结构,由称为节点的对象组成,每个节点包含一个值和一个指向下一个节点的引用。链表的最后一个节点指向null。
在Java中,可以使用节点类来表示链表的节点,节点类中有一个值和指向下一个节点的引用。例如:
```java
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
}
```
然后可以使用链表类来实现链表的操作,比如插入节点、删除节点、查找节点等。例如:
```java
class LinkedList {
ListNode head;
public LinkedList() {
this.head = null;
}
public void insert(int val) {
ListNode newNode = new ListNode(val);
if (head == null) {
head = newNode;
} else {
ListNode current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
public void delete(int val) {
if (head == null) {
return;
}
if (head.val == val) {
head = head.next;
return;
}
ListNode current = head;
while (current.next != null) {
if (current.next.val == val) {
current.next = current.next.next;
return;
}
current = current.next;
}
}
}
```
以上是单向链表的Java实现,可以通过链表类的方法来操作链表,实现插入、删除、查找等功能。链表的节点只需要包含值和指向下一个节点的引用就可以实现链表的基本功能。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)