LeetCodeDiary

A Diary for solving LeetCode problems

View on GitHub
'''
Description: 
Autor: Au3C2
Date: 2021-03-25 11:57:04
LastEditors: Au3C2
LastEditTime: 2021-03-25 11:58:40
'''
# 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: ListNode) -> ListNode:
        if not head: return
        t = ListNode(None)
        t.next = head
        head = t
        preNode = head
        thisNode = preNode.next
        postNode = thisNode.next
        flag = False
        while postNode:
            while postNode and thisNode.val == postNode.val:
                postNode = postNode.next
                preNode.next = postNode
                flag = True
            if not postNode:break
            if not flag:
                preNode = thisNode
            thisNode = postNode
            postNode = postNode.next
            flag = False
        return head.next

# 链表,中等。👆自己写的屑代码,效率差不多,不够简洁
# https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if not head:
            return head
        
        dummy = ListNode(0, head)

        cur = dummy
        while cur.next and cur.next.next:
            if cur.next.val == cur.next.next.val:
                x = cur.next.val
                while cur.next and cur.next.val == x:
                    cur.next = cur.next.next
            else:
                cur = cur.next

        return dummy.next

# 官方题解👆