数据结构:链表(python版)续:带有尾节点引用的单链表
1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 from chapter3.single_linked_list import LNode,LinkedListUnderflow,LList
5 import random
6
7 class LList1(LList):
8 def __init__(self):
9 LList.__init__(self)
10 self._rear = None
11
12 #表头插入
13 def prepend(self, elem):
14 if self._head is None:
15 self._head = LNode(elem)
16 self._rear = self._head
17 else:
18 self._head = LNode(elem, self._head)
19
20 #表尾插入
21 def append(self, elem):
22 if self._head is None:
23 self._head = LNode(elem)
24 self._rear = self._head
25 else:
26 self._rear.next = LNode(elem)
27 self._rear = self._rear.next
28
29 #表头删除
30 def pop(self):
31 if self._head is None:
32 raise LinkedListUnderflow("in pop")
33 e = self._head.elem
34 self._head = self._head.next
35 return e
36 #self._rear不变仍然指向最后一个元素
37
38 #表尾删除
39 def pop_last(self):
40 p = self._head
41 if p is None:
42 raise LinkedListUnderflow("in pop_last")
43 if p.next is None:
44 self._head = None
45 while p.next.next:
46 p = p.next
47 e = p.next.elem
48 p.next = None
49 self._rear = p
50 return e
51
52 if __name__=="__main__":
53 mlist1 = LList1()
54 mlist1.prepend(98)
55 mlist1.printall()
56
57 for i in range(10,20):
58 mlist1.append(random.randint(1,20))
59
60 mlist1.printall()
61
62 for i in mlist1.filter(lambda y: y%2 == 0):
63 print(i)