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

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

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

解题思路

  • 先创建一个新节点,为了便于删除第一个元素;
  • 遍历链表,当有两个相同的元素的时候,取这个元素值,并使用一个循环(当前节点下一个节点存在且值相同),寻找剩下的重复元素,只到删除完成;否则,直接指向下一个元素。

  • 时间复杂度为O(N);
  • 空间复杂度为O(1)。

也可能用数组来解决这个题。

class Solution:
    def deleteDuplicates(self , head: ListNode) -> ListNode:
        # write code here
        if head is None:
            return head

        res = ListNode(-1)
        res.next = head

        cur = res
        while cur.next and cur.next.next:
            if cur.next.val == cur.next.next.val:
                tmp = cur.next.val
                while cur.next != None and cur.next.val == tmp:
                    cur.next = cur.next.next
                
            else:
                
                cur = cur.next
        
        return res.next

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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