接外包,有相关需求的可以联系我:Telegram | Email

Remove Duplicates from Sorted List

该文章创建(更新)于03/15/2022,请注意文章的时效性!

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Solution

Double Pointer / Fast And Slow Pointer

Code

  • submit code
# 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]:
        # Base Condition
        if head == None:
            return head

        fast = head
        slow = head

        while fast != None:
            if fast.val != slow.val:
                # important
                slow = slow.next
                slow.val = fast.val
            fast = fast.next

        slow.next = None
        return head
  • full code to understand
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution:
    def deleteDuplicates(self, head):
        listN = ListNode(head[0])
        tmp = listN
        # Create ListNode From head list
        for m in range(1,head.__len__()):
            listN.next = ListNode(head[m])
            listN = listN.next


        fast = tmp
        slow = tmp

        while fast != None:
            if fast.val != slow.val:
                slow = slow.next
                slow.val = fast.val
            fast = fast.next

        slow.next = None


        return tmp


head = [1,1,2,3,4,5,5]
# head = [1,1,2,2]

S = Solution()
ret = S.deleteDuplicates(head)
while ret != None:
    print(ret.val)
    ret = ret.next


👇 Share | 分享 👇


要不赞赏一下?

微信
支付宝
PayPal
Bitcoin

版权声明 | Copyright

除非特别说明,本博客所有作品均采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。转载请注明转自-
https://www.emperinter.info/2022/03/15/remove-duplicates-from-sorted-list/


要不聊聊?

我相信你准备留下的内容是经过思考的!【勾选防爬虫,未勾选无法留言】

*

*



微信公众号

👉 NewsLetter ❤️ 邮箱订阅 👈

优惠码


阿里云国际版20美元
Vultr10美元
搬瓦工 | Bandwagon应该有折扣吧?
域名 | namesiloemperinter(1美元)