力扣82题:如何删除排序链表中所有重复的元素?
- 内容介绍
- 文章标签
- 相关推荐
本文共计361个文字,预计阅读时间需要2分钟。
题目:给定一个已排序的链表的头 head,删除原始链表中的所有重复数字节点,只留下不同的数字。返回修改后的已排序链表。
来源:力扣(LeetCode)链接:力扣(LeetCode)官网 - 全球极客盛事
代码如下:
pythonclass ListNode: def __init__(self, val=0, next=None): self.val=val self.next=next
def deleteDuplicates(head): if not head: return None
dummy=ListNode(0) dummy.next=head current=dummy
while current.next and current.next.next: if current.next.val==current.next.next.val: current.next=current.next.next else: current=current.next
return dummy.next
题目:
给定一个已排序的链表的头head,删除原始链表中所有重复数字的节点,只留下不同的数字。返回已排序的链表。
来源:力扣(LeetCode)
链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
代码:
# 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]:
list1 = []
while head:
list1.append(head.val)
head = head.next
list1 = [k for k, v in Counter(list1).items() if v == 1]
head = point = ListNode()
for num in list1:
node = ListNode(num)
point.next = node
point = point.next
return head.next
本文共计361个文字,预计阅读时间需要2分钟。
题目:给定一个已排序的链表的头 head,删除原始链表中的所有重复数字节点,只留下不同的数字。返回修改后的已排序链表。
来源:力扣(LeetCode)链接:力扣(LeetCode)官网 - 全球极客盛事
代码如下:
pythonclass ListNode: def __init__(self, val=0, next=None): self.val=val self.next=next
def deleteDuplicates(head): if not head: return None
dummy=ListNode(0) dummy.next=head current=dummy
while current.next and current.next.next: if current.next.val==current.next.next.val: current.next=current.next.next else: current=current.next
return dummy.next
题目:
给定一个已排序的链表的头head,删除原始链表中所有重复数字的节点,只留下不同的数字。返回已排序的链表。
来源:力扣(LeetCode)
链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
代码:
# 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]:
list1 = []
while head:
list1.append(head.val)
head = head.next
list1 = [k for k, v in Counter(list1).items() if v == 1]
head = point = ListNode()
for num in list1:
node = ListNode(num)
point.next = node
point = point.next
return head.next

