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 = data13 self.next = None14 15 16 class LinkedList:17 def __init__(self):18 self.head = None19 self.tail = None20 21 def append(self, data):22 node = Node(data)23 if self.head is None:24 self.head = node25 self.tail = node26 27 else:28 self.tail.next = node29 self.tail = node30 31 def is_zero(self):32 if self.head is None:33 return True34 return False35 36 def len(self):37 if self.head is None:38 return 'Empty'39 else:40 count = 041 while self.head:42 self.head = self.head.next43 count += 144 return count45 46 def iter(self):47 if not self.head:48 return49 50 cur = self.head51 yield cur.data52 while cur.next:53 cur = cur.next54 yield cur.data55 56 def insert(self, idx, value):57 cur = self.head58 cur_idx = 059 while cur_idx < idx - 1:60 cur = cur.next61 if cur is None:62 raise Exception('List length less than index')63 cur_idx += 164 node = Node(value)65 node.next = cur.next66 cur.next = node67 if node.next is None:68 self.tail = node69 70 def remove(self, idx):71 cur = self.head72 cur_idx = 073 while cur_idx < idx - 1:74 cur = cur.next75 if cur is None:76 raise Exception('List length less than index')77 cur_idx += 178 cur.next = cur.next.next79 if cur.next is None:80 self.tail = cur81 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)