剑指 Offer 18. 删除链表的节点
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
# 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:
tem = head
if tem.val == val:
return(head.next)
while tem and tem.next:#注意这里的判定条件,不能写成while tem,因为这样当链表尾节点是要删除的节点时,
#你还得需要再重新遍历;而这样写不需要,因为永远不会循环到为节点,只会循环到为节点前一个节点,而当循环到伪节点前一个节点时,通过下面的判断语句直接将tem.next 指向tem.next.next,就跳过了为节点,其实就是指向了None
if tem.next.val == val:
tem.next = tem.next.next
tem = tem.next
return(head)
时间复杂度:O(n),因为最坏要遍历所有节点;空间复杂度:O(1),链表只是占用了一个指针的空间
也可以用双指针形式
#双指针
#双指针
pre, cur = head, head.next
result = pre
if pre.val == val:
return(cur)
while cur:
if cur.val == val:
pre.next = cur.next
break
else:
pre = cur
cur = cur.next
return(result)