原题链接:Remove Duplicates from Sorted List
代码如下:(python)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class 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