给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
示例 1:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
思路:
1.如果第一个结点刚好是要删除的结点,则head.val = val;
2.初始化 pre = head , cur = head.next;
2.如果不是,通过循环,继续往下寻找。当找到。即可删除
特例:第一个就为要删除的结点
这里要定义两个指针 (head指向第一个结点)
cur: 表示要删除的结点
pre : 表示要删除结点的前一个结点
关键操作: pre.next = cur.next;
代码实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head.val == val) return head.next;
ListNode pre = head, cur = head.next;
while(cur != null && cur.val != val) {
pre = cur;
cur = cur.next;
}
if(cur != null) pre.next = cur.next;
return head;
}
}