题目描述:

给定一个没有排序的链表,去掉重复项,并保留原顺序 如: 1->3->1->5->5->7,去掉重复项后变为:1->3->5->7
方法:
1.顺序删除
由于这种方法采用双重循环对链表进行遍历,因此,时间复杂度为O(n**2)
在遍历链表的过程中,使用了常数个额外的指针变量来保存当前遍历的结点,前驱结点和被删除的结点,所以空间复杂度为O(1)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/1/15 20:55
# @Author : buu
# @Software: PyCharm
# @Blog :https://blog.csdn.net/weixin_44321080
class LNode:
def __init__(self, x):
self.data = x
self.next = None
def removeDup(head):
"""
对带头结点的无序单链表删除重复的结点
顺序删除:通过双重循环直接在链表上进行删除操作
即,外层循环用一个指针从第一个结点开始遍历整个链表,内层循环从外层指针指向的下一个结点开始,
遍历其余结点,将与外层循环遍历到的的指针所指的结点的数据域相同的结点删除
:param head: 头指针
:return:
"""
if head is None or head.next is None:
return
outerCur = head.next
innerCur = None
innerPre = None
while outerCur is not None:
innerCur = outerCur.next
innerPre = outerCur
while innerCur is not None:
if outerCur.data == innerCur.data:
innerPre.next = innerCur.next
innerCur = innerCur.next
else:
innerPre = innerCur
innerCur = innerCur.next
outerCur = outerCur.next
if __name__ == '__main__':
i = 1
head = LNode(6)
tmp = None
cur = head
while i < 7:
if i % 2 == 0:
tmp = LNode(i + 1)
elif i % 3 == 0:
tmp = LNode(i - 2)
else:
tmp = LNode(i)
cur.next = tmp
cur = tmp
i += 1
print("before removeDup:")
cur = head.next
while cur is not None:
print(cur.data, end=' ')
cur = cur.next
removeDup(head)
print("\nafter removeDup:")
cur = head.next
while cur is not None:
print(cur.data, end=' ')
cur = cur.next另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。