面试题 02.01. 移除重复节点

编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。

示例1:

输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:

输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:

链表长度在[0, 20000]范围内。
链表元素在[0, 20000]范围内。
进阶:

如果不得使用临时缓冲区,该怎么解决?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeDuplicateNodes(self, head: ListNode) -> ListNode:
        def listToStack(l: ListNode) -> list:
            stack, c = [], l
            while c:
                stack.append(c.val)
                c = c.next
            return stack
        li=listToStack(head)
        if li==[]:
            return []
        result = ListNode(li[0])
        set_li=[]
        for i in li:
            if i not in set_li:
                set_li.append(i)
        c = result
        
        for item in set_li[1:]:
            c.next = ListNode(item)
            c = c.next

        return result

 

 

 

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeDuplicateNodes(self, head: ListNode) -> ListNode:
        _set=set()
        pre=ListNode(-1)
        pre.next=head
        while pre.next:
            if pre.next.val in _set:
                
                pre.next=pre.next.next
            else:
                _set.add(pre.next.val)
                pre=pre.next

        return head

 

posted @ 2020-09-03 23:39  XXXSANS  阅读(164)  评论(0编辑  收藏  举报