题目
给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。 示例 1:
代码语言:javascript复制输入:head = [1,1,2]
输出:[1,2]
示例 2:
代码语言:javascript复制输入:head = [1,1,2,3,3]
输出:[1,2,3]
提示: 链表中节点数目在范围 [0, 300] 内 -100 <= Node.val <= 100 题目数据保证链表已经按升序 排列 来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/remove-duplicates-from-sorted-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法
遍历
代码语言:javascript复制class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return head
result = head
while result is not None and result.next is not None:
if result.val == result.next.val:
result.next = result.next.next
else:
result = result.next
return head
递归
代码语言:javascript复制class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head
head.next = self.deleteDuplicates(head.next)
return head.next if head.val == head.next.val else head