【题目】
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。
返回同样按升序排列的结果链表。
【示例 1】
输入:head = [1,1,2]
输出:[1,2]
【示例 2】
输入:head = [1,1,2,3,3]
输出:[1,2,3]
【提示】
链表中节点数目在范围 [0, 300] 内
-100 <= Node.val <= 100
题目数据保证链表已经按升序排列
【代码】
【Python】

class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
s=set()
pre,cur=head,head.next
s.add(pre.val)
while cur:
if cur.val not in s:
s.add(cur.val)
pre=pre.next
else:
pre.next=cur.next
cur=cur.next
return head
【方法2】

class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return head
cur = head
while cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
该博客讨论了如何删除已按升序排列的链表中的重复元素,以确保每个元素仅出现一次。提供了两种Python解决方案,分别通过使用集合和简单的节点遍历来实现。这两种方法都能够有效地更新链表,保持其升序排列。
817

被折叠的 条评论
为什么被折叠?



