您的位置:首页 > 编程语言 > Python开发

链表问题---删除无序单链表中值重复出现的节点

2017-11-19 10:28 246 查看
【题目】

  给定一个无序单链表的头节点head,删除其中值重复出现的节点。

  请按以下要求实现两种方法。

方法一。时间复杂度O(N)。

方法二。空间复杂度O(1)。

【基本思路】

  方法一。利用哈希表,依次遍历每一个节点,如果这个节点的值已经存在于哈希表中,将该节点删除;否则,将该节点的值添加到哈希表中。代码实现如下:

#python3.5
def removeRepeatNode(head):
if head == None or head.next == None:
return head
hashSet = set()
pre = head
cur = head.next
hashSet.add(head.val)
while cur != None:
next = cur.next
if cur.val not in hashSet:
hashSet.add(cur.val)
pre = cur
else:
pre.next = next
cur = next


  方法二。时间复杂度O(N2),空间复杂度O(1)。

  遍历每一个节点,假设遍历到位置i,从i位置开始遍历之后所有的节点,把值相同的节点的删除。代码实现如下:

def removeRepeatNode2(head):
if head == None or head.next == None:
return head
while head != None:
pre = head
cur = head.next
while cur != None:
if cur.val == head.val:
pre.next = cur.next
else:
pre = cur
cur = cur.next
head = head.next
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 python