用java实现单链表和单链表的增、删、改、插
时间: 2023-04-21 22:06:37 浏览: 91
实现单链表的建立、插入与删除
3星 · 编辑精心推荐
入、查找等操作,可以参考以下代码实现:
单链表的节点类:
```
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
```
单链表类:
```
public class LinkedList {
private ListNode head;
public LinkedList() {
head = null;
}
// 增加节点
public void addNode(int val) {
ListNode newNode = new ListNode(val);
if (head == null) {
head = newNode;
} else {
ListNode cur = head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = newNode;
}
}
// 删除节点
public void deleteNode(int val) {
if (head == null) {
return;
}
if (head.val == val) {
head = head.next;
return;
}
ListNode cur = head;
while (cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
return;
}
cur = cur.next;
}
}
// 修改节点
public void modifyNode(int oldVal, int newVal) {
ListNode cur = head;
while (cur != null) {
if (cur.val == oldVal) {
cur.val = newVal;
return;
}
cur = cur.next;
}
}
// 插入节点
public void insertNode(int pos, int val) {
ListNode newNode = new ListNode(val);
if (pos == 0) {
newNode.next = head;
head = newNode;
return;
}
ListNode cur = head;
for (int i = 0; i < pos - 1 && cur != null; i++) {
cur = cur.next;
}
if (cur == null) {
return;
}
newNode.next = cur.next;
cur.next = newNode;
}
// 查找节点
public boolean searchNode(int val) {
ListNode cur = head;
while (cur != null) {
if (cur.val == val) {
return true;
}
cur = cur.next;
}
return false;
}
// 打印链表
public void printList() {
ListNode cur = head;
while (cur != null) {
System.out.print(cur.val + " ");
cur = cur.next;
}
System.out.println();
}
}
```
使用示例:
```
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addNode(1);
list.addNode(2);
list.addNode(3);
list.printList(); // 输出:1 2 3
list.deleteNode(2);
list.printList(); // 输出:1 3
list.modifyNode(1, 4);
list.printList(); // 输出:4 3
list.insertNode(1, 2);
list.printList(); // 输出:4 2 3
System.out.println(list.searchNode(2)); // 输出:true
System.out.println(list.searchNode(5)); // 输出:false
}
```
阅读全文