链表-python-leetcode 83 Remove Duplicates from Sorted List

来源:互联网 发布:中国地质大学北京知乎 编辑:程序博客网 时间:2024/06/03 15:20

原题链接:Remove Duplicates from Sorted List



代码如下:(python)

# 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        """'''思路:遍历链表,把非重复的元素添加进集合s中,并将该节点添加到链表original中head_first用于跟踪head,指向已变量的节点中最后一个非重复节点遍历结束,将head_first的next置为None  Time Complexity:O(N)'''        original=ListNode(0)        head_first=original        s=set()        while head!=None:            if head.val not in s:                s.add(head.val)                head_first.next=head                head_first=head_first.next            head=head.next        head_first.next=None        return original.next


c++版参见:c++版

原创粉丝点击