双向链表的简单实现

 

双向链表的特点是:第一个元素的 prev 是None

 

 

 1 # 双向链表:
 2 class Node:
 3     def __init__(self,  node=None, prev=None,  next=None):
 4         # 注意顺序,因为实例化,一般不会关键字传参, 如果node= None(1) 1 是给node形参的,如果形参列表不同,则会出现异常
 5         self.prev = prev
 6         self.node = node
 7         self.next = next
 8 
 9     def __repr__(self):
10         return '{} <-- {} --> {}'.format(
11             self.prev.node if self.prev else None,
12             self.node,
13             None if self.next is None else self.next.node)
14 
15 class DoubleLinkList:
16     def __init__(self, head= None, tail=None):
17         self.head = head
18         self.tail = tail
19         self.lens = 0
20 
21     def append(self, node):
22         node = Node(node)
23         if self.head is None:
24             self.head = node
25         else:
26             self.tail.next = node
27             node.prev = self.tail
28         self.tail = node
29         self.lens += 1
30 
31     def iternode(self, reverse=True):
32         if self.head is None:
33             raise  Exception('This is a Emppty linklist')
34         current = self.head if reverse else self.tail
35         while current:
36             yield  current
37             current = current.next if reverse else current.prev
38 
39     def __iter__(self):
40         if self.head is None:
41             raise  Exception('This is a Emppty linklist')
42         current = self.head
43         while current:
44             yield current
45             current = current.next
46 
47     def __getitem__(self, index):
48         reverse = True if index>=0 else False
49         start = 0 if index>=0 else 1
50         for i, v in enumerate(ll.iternode(reverse), start):
51             if i == abs(index):
52                 return v
53 
54     def __setitem__(self, index, value):
55         ll[index].node = value
56 
57     def __len__(self):
58         return self.len
59 
60     def remove(self):
61         pass
62         # 先判断是否为空
63         # 需要遍历,利用iter
64         # 注意是中间,第一个,还是尾部删除
65 
66     def pop(self):
67         pass
68         # 值删除尾部,self.tail.next = None
69 
70     def insert(self, index):
71         pass
72         # 类似于remove
73     
74 
75 
76 ll = DoubleLinkList()
77 ll.append(1)
78 ll.append(2)
79 ll.append(3)
80 ll.append(4)
81 ll.append(5)
82 
83 for i in ll.iternode(False):
84     print(i)
85 print('----'* 20)
86 print(ll[-1])
87 
88 ll[-1] = 10000
89 print(ll[-1])

 部分打印结果:

  

posted @ 2018-09-25 16:38  JerryZao  阅读(184)  评论(0编辑  收藏  举报