题解 | #删除有序链表中重复的元素-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

全部评论

相关推荐

Lorn的意义:你这种岗位在中国现在要么牛马天天加班,要么关系户进去好吃好喝,8年时间,真的天翻地覆了,对于资本来说你就说一头体力更好的牛马,哎,退伍没有包分配你真的亏了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务