给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
注意:此题对比原题有改动;题目保证链表中节点的值互不相同
示例 1:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
这个题需要删除节点并改变链表的连接,且是单向链表,因此需要设置指针。可以设置但指针也可以设置双指针。
方法1 双指针
思路
既然要删除节点,那么主要有两步:
1. 定位:遍历列表,直到出现(当前节点的值==value)或(遍历完成);
2. 删除:因为是单向列表,所以要设置指针。对于双指针pre和cur,设其连接关系为pre-->cur-->cur.next,;则若cur是需要删除的节点,则只需要pre.next = cur.next即可。
遍历过程只需要pre ,cur = cur, cur.next
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, head: ListNode, val: int) -> ListNode:
if head.val == val: # specific situation, return directly
return head.next
pre ,cur = head, head.next
while(cur):
if cur.val == val: # find node
# delete node
pre.next = cur.next
break
# update
pre, cur = cur, cur.next
return head
方法2 单指针
思路
思路与方法1类似
1. 定位:遍历列表,直到出现(当前节点的值==value)或(遍历完成);
2. 删除:因为是单向列表,所以要设置指针。对於单指针cur,设其连接关系为cur-->cur.next-->cur.next.next,;则若cur.next是需要删除的节点,则只需要xur.next = cur.next.next即可。
代码
class Solution:
def deleteNode(self, head: ListNode, val: int) -> ListNode:
if head.val == val: # specific situation, return directly
return head.next
cur = head
while(cur):
if cur.next.val == val: # localization
cur.next = cur.next.next # delete
break # return directly
cur = cur.next # next node
return head
结果
总结
两种方法的时间复杂度均为O(N);
空间复杂度均为O(1)