1、题目描述:
2、题解:
定义一个哈希集合,一个指向head的temp,然后进行链表的遍历:
如果下一个节点的值不在哈希集合中,就添加进去,说明没有重复,保留此节点,赋值temp = temp.next;
否则就跳过下一个节点,之间令指针指向下下个节点,也就是temp.next = temp.next.next
# 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:
hashset = set()
if not head or not head.next:
return head
temp = head
hashset.add(head.val)
while temp and temp.next:
if temp.next.val not in hashset:
hashset.add(temp.next.val)
temp = temp.next
else:
temp.next = temp.next.next
# print(hashset)
return head
3、复杂度分析:
时间复杂度:O(N)
空间复杂度:O(N)