题解 | #删除有序链表中重复的元素-II# 去重重建链表

删除有序链表中重复的元素-II

https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024

# 去重 + 重建链表
class Solution:
    def deleteDuplicates(self , head: ListNode) -> ListNode:
        if not head or not head.next:
            return head

        l1 = []
        l2 = []
        while head:
            l1.append(head.val)
            head = head.next
        
        tmp = l1[0]
        l2.append(tmp)
        for i in range(1, len(l1)):
            if l1[i] == tmp:
                if l2 and l2[-1] == tmp:
                    l2.pop()
                continue
            else:
                tmp = l1[i]
                l2.append(tmp)
        
        dummy = ListNode(0)
        cur = dummy
        for i, v in enumerate(l2):
            node = ListNode(v)
            cur.next = node
            cur = cur.next
        return dummy.next

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务