题目
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
注意:此题对比原题有改动
示例 1:
1
2
3 输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.示例 2:
1
2
3 输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.说明:
- 题目保证链表中节点的值互不相同
- 若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
要考虑节点值不存在的情况。
1 | /** |
这种思路是从头开始匹配节点,匹配到则删除。
迭代写法思路为:
- 先设置一个伪头节点用于边界情况处理
- 当前节点
curr
,查询curr->next
是否是我们需要删除的节点- 如果下个节点为
nullptr
说明已经到达链表尾部,此时要删除的元素不在链表中 - 如果下个节点存在且需要删除,那么把当前节点的
next
指向下个结点的next
,并把下个节点指向nullptr
- 如果下个节点存在且不需要删除,那么迭代当前节点
- 如果下个节点为
1 | /** |
注意返回值一定是伪首节点的下个节点。
- 时间复杂度 $O(N)$
- 空间复杂度 $O(1)$