题目:
给定一个已排序的链表的头
head
, 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。来源:力扣(LeetCode)
链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
示例:
示例 1:
输入:head = [1,1,2]
输出:[1,2]
示例 2:输入:head = [1,1,2,3,3]
输出:[1,2,3]
解法:
判断当前值和后一个值是否相等,相等就修改指针,指向再后面一个:head.next = head.next.next;不相等,就移动当前指针指向后一个:head = head.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]: point = head if not head: return point while head.next: if head.val == head.next.val: head.next = head.next.next else: head = head.next return point