Given the head
of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Example 1:
Input: head = [1,2,3,3,4,4,5] Output: [1,2,5]
Example 2:
Input: head = [1,1,1,2,3] Output: [2,3]
Constraints:
- The number of nodes in the list is in the range
[0, 300]
. -100 <= Node.val <= 100
- The list is guaranteed to be sorted in ascending order.
这题跟LeetCode 83. Remove Duplicates from Sorted List 的不同之处在于本题要求把具有相同值的所有节点都删掉。同样的对于一个排好序的链表,值相同的节点在链表中一定都是连续的,因此对于一个节点可以一次找出值与其相同的所有节点,然后把它们删掉。本题也有迭代和递归两种解法。
迭代法:定义两个指针cur和pre分别指向当前节点及其父节点,遍历整个链表。对于当前节点,判断当前节点之后是否有与其值相等的节点,由于相等节点一定是连续存在的,可以用一个指针end指向最后一个与当前节点值相等的节点,如果end和cur指向的不是同一个节点说明存在与当前节点值相等的节点,需要把它们全部删除(pre.next指向end.next),指针pre不变,指针cur更新为指向end.next,进入下一次循环;如果不存在与当前节点值相等的节点,指针pre指向cur,cur指向cur.next,进入下一次循环。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
preHead = ListNode(0, head)
pre, cur = preHead, head
while cur:
end = cur
while end.next and end.next.val == cur.val:
end = end.next
if end != cur:
pre.next = end.next
cur = end.next
else:
pre = cur
cur = cur.next
return preHead.next
递归法:对于递归调用的输入链表,如果节点个数小于等于1,则不用做任何处理直接返回头节点指针;如果节点个数大于等于2,需要判断头节点head之后是有与其值相等的节点。定义一个指针cur指向头节点head然后开始查找使cur指向第一个与头节点head.val值不相等的节点,然后递归调用处理从cur(第一个与头节点head值不相等的节点)开始的链表,返回一个新头newHead。如果指针cur指向的不是head.next,说明存在多个值相同的节点,需要把它们全删掉,直接返回新头节点newHead;如果指针cur指向的是head.next,说明不存在值相同的多个节点,旧头节点需保留并且head.next指向新头节点newHead,返回head。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
cur = head
while cur and cur.val == head.val:
cur = cur.next
newHead = self.deleteDuplicates(cur)
if cur == head.next:
head.next = newHead
else:
head = newHead
return head