题目
思考:
记录目标节点前的位置before,以及目标节点以后的位置after,再用before.next=after,不过还是遇到了老问题!before走着走着,就丢掉了前面的点了!需要一个dummy=before,指向同一个地址,再让before指向after,就好啦。
其实不要after节点也可以呢,before指向cur.next也是一样的道理呢。
class Solution:
def deleteNode(self , head: ListNode, val: int) -> ListNode:
if head is None:
return None
if head.val == val:
return head.next
curr = head
dummy = before = head
while curr:
if curr.val == val:
curr = curr.next
break
else:
before = curr
curr = curr.next
before.next = curr
return dummy
看了一下参考答案,只用到了两个指针,head一直往后走,遇到目标值就head.next = head.next.next
。
class Solution:
def deleteNode(self , head: ListNode, val: int) -> ListNode:
# write code here
cur=head
while head and head.next:
if head.next.val==val:
if head.next.next==None:
head.next=None
return cur
else:
head.next=head.next.next
if head.val==val:
return head.next
head=head.next
return cur