LintCode 217 [Remove Duplicates from Unsorted List]

原题

设计一种方法,从无序链表中删除重复项。

样例
给出 1->3->2->1->4. �返回 1->3->2->4

解题思路

  • 遍历链表,用一hash表记录出现过的节点的值,如果出现过则删除,未出现过则加入hash表

完整代码

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    # @param head, a ListNode
    # @return a ListNode
    def removeDuplicates(self, head):
        # Write your code here
        if not head:
            return head
        
        res = head
        map = {}
        map[head.val] = True
        
        while head.next != None:
            if head.next.val not in map:
                map[head.next.val] = True
                head = head.next
            else:
                head.next = head.next.next

        return res

你可能感兴趣的:(LintCode 217 [Remove Duplicates from Unsorted List])