美文网首页
19删除排序链表中的重复元素

19删除排序链表中的重复元素

作者: Jachin111 | 来源:发表于2020-07-27 12:53 被阅读0次

    给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

    示例 1:
    输入: 1->1->2
    输出: 1->2

    示例 2:
    输入: 1->1->2->3->3
    输出: 1->2->3

    class Solution:
        def deleteDuplicates(self, head: ListNode) -> ListNode:
            node=head
            while node and node.next:
                if node.val==node.next.val:
                    node.next=node.next.next
                else:
                    node=node.next
            return head
    
    class Solution:
        def deleteDuplicates(self, head: ListNode) -> ListNode:
            dummy_head = ListNode(None)
            dummy_head.next = head
    
            pre = dummy_head
            cur = head
    
            while cur:
                if pre and cur.val == pre.val:
                    pre.next = cur.next
                    cur.next = None
                    cur = pre.next
                    continue
    
                pre = cur
                cur = cur.next
            return dummy_head.next
    
    class Solution:
        def deleteDuplicates(self, head: ListNode) -> ListNode:
            if head is None or head.next is None:
                return head
            
            child = self.deleteDuplicates(head.next)
            if child and head.val == child.val:
                head.next = child.next
                child.next = None
                
            return head
    

    来源:力扣(LeetCode)

    相关文章

      网友评论

          本文标题:19删除排序链表中的重复元素

          本文链接:https://www.haomeiwen.com/subject/xllzlktx.html