一般,链表中删除元素的题都会使用伪头指针法 即,为了防止原链表的头节点即为待删除元素, 我们先在链表的头部附上一个肯定不会被删除的伪头指针 (如此题中,每个节点的val均为数字,则我们让伪头指针的val为字符串,它一定不会被删除) 此后用一个指针last指向上一个肯定不会被删除的节点 再用一个指针cur指向带判断的节点 对于中间的节点 保留其在链表的条件是 cur的值 和cur的父节点的值不相等 以及 cur的值和其next的值不想等 因此,我们需要在遍历链表中,在每一次cur = cur.next之前记住cur的值
当cur.next == None时,单拎出来判断即可
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: faker = ListNode('x') faker.next = head cur = head last = faker father_val = faker.val while cur != None: if cur.next == None and (cur.val == last.val or cur.val == father_val): last.next = None return faker.next elif cur.next == None: if cur.val != father_val: last.next = cur return faker.next elif cur.val != father_val and cur.val != cur.next.val: last.next = cur last = cur father_val = cur.val cur = cur.next last.next = None elif cur.val == father_val: cur = cur.next elif cur.val == cur.next.val: father_val = cur.val cur = cur.next return faker.next下面的方法也可以
class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: faker = ListNode('x') faker.next = head cur = faker last = faker while cur != None: print(cur) if last.val != cur.val: last = cur cur = cur.next else: father_val = last.val while cur != None: if cur.val == last.val or cur.val == father_val: pass elif cur.next != None and cur.val == cur.next.val: father_val = cur.val else: last.next = cur last = cur cur = cur.next if cur == None: last.next = None return faker.next