python之数据结构链表实现方式

 1 #!/usr/bin/env python
 2 # ---------------------------------------
 3 # author : Geng Jie
 4 # email  : gengjie@outlook.com
 5 #
 6 # Create Time: 2016/3/16 22:05
 7 # ----------------------------------------
 8 
 9 
10 class Node():
11     def __init__(self, data):
12         self.data = data
13         self.next = None
14 
15 
16 class LinkedList:
17     def __init__(self):
18         self.head = None
19         self.tail = None
20 
21     def append(self, data):
22         node = Node(data)
23         if self.head is None:
24             self.head = node
25             self.tail = node
26 
27         else:
28             self.tail.next = node
29             self.tail = node
30 
31     def is_zero(self):
32         if self.head is None:
33             return True
34         return False
35 
36     def len(self):
37         if self.head is None:
38             return 'Empty'
39         else:
40             count = 0
41             while self.head:
42                 self.head = self.head.next
43                 count += 1
44             return count
45 
46     def iter(self):
47         if not self.head:
48             return
49 
50         cur = self.head
51         yield cur.data
52         while cur.next:
53             cur = cur.next
54             yield cur.data
55 
56     def insert(self, idx, value):
57         cur = self.head
58         cur_idx = 0
59         while cur_idx < idx - 1:
60             cur = cur.next
61             if cur is None:
62                 raise Exception('List length less than index')
63             cur_idx += 1
64         node = Node(value)
65         node.next = cur.next
66         cur.next = node
67         if node.next is None:
68             self.tail = node
69 
70     def remove(self, idx):
71         cur = self.head
72         cur_idx = 0
73         while cur_idx < idx - 1:
74             cur = cur.next
75             if cur is None:
76                 raise Exception('List length less than index')
77             cur_idx += 1
78         cur.next = cur.next.next
79         if cur.next is None:
80             self.tail = cur
81 
82 
83 if __name__ == '__main__':
84     linked_list = LinkedList()
85     for i in range(10):
86         linked_list.append(i)
87 
88     print(linked_list.len())
89 
90     # print(linked_list.is_zero())
91     # linked_list.insert(3, 30)
92     # linked_list.remove(4)
93     # for node in linked_list.iter():
94     #     print(node)

 

posted @ 2016-03-17 00:30  Topic  阅读(228)  评论(0编辑  收藏  举报
转载请注明出处. 作者: 运维的自我修养 地址: http://www.cnblogs.com/topicjie/