算法-简单-删除链表节点:
- 自定义一个链表结构
- 如何打印链表数据,使其可视化
- 删除节点
其他的还有添加,修改等,可以基于这个基本的结构调整
/**
* @description: 给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
* 返回删除后的链表的头节点。
*/
public class 删除链表的节点 {
/**
* 输入: head = [4,5,1,9], val = 5
* 输出: [4,1,9]
* 解释: 给定你链表中值为的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
*/
public static void main(String[] args) {
// 1. 构建一个链表
ListNode head = new ListNode(4);
ListNode listNode1 = new ListNode(5);
head.next = listNode1;
ListNode listNode2 = new ListNode(1);
listNode1.next = listNode2;
ListNode listNode3 = new ListNode(9);
listNode2.next = listNode3;
//打印链表
printListNode(head);
// 2. 删除节点
ListNode result = deleteNode(head, 9);
//打印链表
printListNode(result);
}
public static ListNode deleteNode(ListNode head, int val) {
if (head == null) {
return null;
}
if (head.val == val) {
head = head.next;
return head;
}
ListNode tmp = head;
while (tmp != null && tmp.next != null) {
if (tmp.next.val == val) {
tmp.next = tmp.next.next;
} else {
tmp = tmp.next;
}
}
return head;
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static void printListNode(ListNode head) {
while (head.next != null) {
System.out.print(head.val + "->");
head = head.next;
}
System.out.println(head.val + "->" + null);
}
}