「这是我参与2022首次更文挑战的第24天,活动详情查看:2022首次更文挑战」
删除链表的节点 Delete node in a linked list
LeetCode传送门剑指 Offer 18. 删除链表的节点
题目
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.
Given a head pointer to a singly linked list and the value of a node to delete, define a function to delete that node.
Returns the head node of the deleted list.
Example:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
Constraints:
- The value of each node in the list is unique.
思考线
解题思路
我们在这道题中所获得的线索是
- 链表的
head节点 - 要删除节点的
val值
我们要做的事是:删除给定val的节点。同时返回头结点。
考虑到我们可能删除头部的节点,所以为了避免分类讨论的情况,我们可以在开始时写一个dummyHead来统一情况,以便写出简单清晰的代码,在处理完成删除操作后,我们只需要返回dummyHead.next即可。
同时若要通过head节点删除一个对应的节点,我们要找到删除节点的前一个节点,然后让其指针指向删除节点的下一个节点即可。所以我们最好使用一个while循环,当h.next.val ===val时,我们就找到了删除节点的前一个节点。
根据以上思路,我们完成代码
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function deleteNode(head: ListNode | null, val: number): ListNode | null {
const dummHead = new ListNode(-1, head);
let h = dummHead;
while(h.next.val !== val) {
h = h.next;
}
h.next = h.next.next;
return dummHead.next
};
时间复杂度
O(N): N为链表的长度,最差的情况系我们要删除的是最后一个元素,所以复杂度为N。
这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。