编写函数,将单链表中具有相同元素值的节点删除(只保留一个)

时间复杂度:0(n)

 

 1 #!/usr/bin/env python3
 2 
 3 class LNode(object):
 4         def __init__(self, elem, next_):
 5                 self.elem = elem
 6                 self.next = next_
 7 
 8 class Rm_Repetition_List(object):
 9         def __init__(self):
10                 self.head = None
11                 self.num = 0
12 
13         def is_empty(self):
14                 return self.head is None
15 
16         def count(self):
17                 return self.num
18 
19         def prepend(self, elem):
20                 self.head = LNode(elem, self.head)
21 
22         def bianli(self):
23                 p = self.head
24                 li = []
25                 while p:
26                         li.append(p.elem)
27                         p = p.next
28                 return li
29 
30         def rm_repetition(self):
31                 li = []
32                 if self.is_empty():
33                         raise ValueError
34                 li.append(self.head.elem)
35                 p = self.head.next
36                 pre = self.head
37                 while p:
38                         if p.elem in li:
39                                 pre.next = p.next
40                                 p = p.next
41                         else:
42                                 li.append(p.elem)
43                                 pre = p
44                                 p = p.next
45 
46 if __name__ == '__main__':
47         l = Rm_Repetition_List()
48         ll = [1,3,2,5,1,2,7,5,2]
49         for i in ll:
50                 l.prepend(i)
51         print(l.bianli())
52         l.rm_repetition()
53         print(l.bianli())

 

结果:

[2, 5, 7, 2, 1, 5, 2, 3, 1]
[2, 5, 7, 1, 3]

转载于:https://www.cnblogs.com/xautxuqiang/p/6414685.html

你可能感兴趣的:(数据结构与算法,c/c++,python)