leetcode: 83. Remove Duplicates from Sorted List

来源:互联网 发布:海知智能孙胜男 编辑:程序博客网 时间:2024/06/16 19:21

Q

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

AC

# Definition for singly-linked list.class ListNode(object):    def __init__(self, x):        self.val = x        self.next = Noneclass Solution(object):    def deleteDuplicates(self, head):        """        :type head: ListNode        :rtype: ListNode        """        t_point = head        while t_point:            while t_point.next and t_point.next.val == t_point.val:                t_point.next = t_point.next.next            t_point = t_point.next        return head# Time:  O(n)# Space: O(1)class ListNode(object):    def __init__(self, x):        self.val = x        self.next = Noneclass Solution2(object):    def deleteDuplicates(self, head):        """        :type head: ListNode        :rtype: ListNode        """        cur = head        while cur:            runner = cur.next            while runner and runner.val == cur.val:                runner = runner.next            cur.next = runner            cur = runner        return head    def deleteDuplicates2(self, head):        """        :type head: ListNode        :rtype: ListNode        """        if not head: return head        if head.next:            if head.val == head.next.val:                head = self.deleteDuplicates(head.next)            else:                head.next = self.deleteDuplicates(head.next)        return headif __name__ == "__main__":    head, head.next, head.next.next, head.next.next.next, head.next.next.next.next \        = ListNode(1), ListNode(1), ListNode(2), ListNode(3), ListNode(3)    assert Solution().deleteDuplicates(head).val == 1


阅读全文
0 0