力扣82题:如何用Python3删除排序链表中所有重复的元素?
- 内容介绍
- 文章标签
- 相关推荐
本文共计449个文字,预计阅读时间需要2分钟。
题目:给定一个已排序的链表的头节点 head,删除原链表中所有重复的数字节点,只留下不同的数字。返回修改后的排序链表。
内容:pythonclass ListNode: def __init__(self, val=0, next=None): self.val=val self.next=next
def deleteDuplicates(head): if not head: return head
dummy=ListNode(0) dummy.next=head prev=dummy curr=head
while curr and curr.next: if curr.val==curr.next.val: while curr.next and curr.val==curr.next.val: curr=curr.next prev.next=curr.next else: prev=curr curr=curr.next
return dummy.next
测试代码def printList(head): while head: print(head.val, end= -> ) head=head.next print(None)
创建链表node1=ListNode(1)node2=ListNode(1)node3=ListNode(2)node4=ListNode(3)node5=ListNode(3)node6=ListNode(4)node1.next=node2node2.next=node3node3.next=node4node4.next=node5node5.next=node6
删除重复节点result=deleteDuplicates(node1)
打印结果printList(result)
来源:力扣(LeetCode)链接:力扣(LeetCode)官网 - 全球极客翘楚,编程挑战平台
题目:
给定一个已排序的链表的头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
本文共计449个文字,预计阅读时间需要2分钟。
题目:给定一个已排序的链表的头节点 head,删除原链表中所有重复的数字节点,只留下不同的数字。返回修改后的排序链表。
内容:pythonclass ListNode: def __init__(self, val=0, next=None): self.val=val self.next=next
def deleteDuplicates(head): if not head: return head
dummy=ListNode(0) dummy.next=head prev=dummy curr=head
while curr and curr.next: if curr.val==curr.next.val: while curr.next and curr.val==curr.next.val: curr=curr.next prev.next=curr.next else: prev=curr curr=curr.next
return dummy.next
测试代码def printList(head): while head: print(head.val, end= -> ) head=head.next print(None)
创建链表node1=ListNode(1)node2=ListNode(1)node3=ListNode(2)node4=ListNode(3)node5=ListNode(3)node6=ListNode(4)node1.next=node2node2.next=node3node3.next=node4node4.next=node5node5.next=node6
删除重复节点result=deleteDuplicates(node1)
打印结果printList(result)
来源:力扣(LeetCode)链接:力扣(LeetCode)官网 - 全球极客翘楚,编程挑战平台
题目:
给定一个已排序的链表的头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

