单向链表的python实现
1 class Node(): 2 def __init__(self,item): 3 #初始化这个节点,值和下一个指向 4 self.item = item 5 self.next = None 6 7 class SingleLinklist(): 8 def __init__(self): 9 #初始化这个单链表的头指针为空 10 self._head = None 11 12 def length(self): 13 #获取这个链表的长度 14 count = 0 15 cur = self._head 16 while cur != None: 17 count+=1 18 cur = cur.next 19 return count 20 21 def is_empty(self): 22 """判断是否为空""" 23 return self._head == None 24 25 def add(self,item): 26 """在头部添加元素""" 27 node = Node(item) 28 node.next = self._head 29 self._head = node 30 31 def append(self,item): 32 """在尾部添加元素""" 33 cur = self._head 34 node = Node(item) 35 while cur != None: 36 cur = cur.next 37 cur.next = node 38 39 def insert(self,pos,item): 40 """在选定的位置添加元素""" 41 cur = self._head 42 node = Node(item) 43 count = 0 44 if pos <= 0: 45 self.add(item) 46 elif pos > (self.length()-1): 47 self.append(item) 48 else: 49 while count < (pos -1): 50 count+=1 51 cur = cur.next 52 node.next = cur.next 53 cur.next = node 54 55 56 def travel(self): 57 """遍历整个链表""" 58 cur = self._head 59 while cur != None: 60 print(cur.item,end=" ") 61 cur = cur.next 62 print(" ") 63 64 def remove(self,item): 65 """删除链表""" 66 cur = self._head 67 pre =None 68 while cur != None: 69 if cur.item == item: 70 if not pre: 71 self._head = cur.next 72 break 73 else: 74 pre.next = cur.next 75 else: 76 pre = cur # 77 cur = cur.next 78 79 def search(self,item): 80 """查找某个节点""" 81 cur = self._head 82 while cur != None: 83 if cur.item == item: 84 print("找到这个元素了") 85 return True 86 cur = cur.next 87 print("抱歉没有这个元素") 88 return False 89 90 singlistdemo = SingleLinklist() 91 singlistdemo.add(1) 92 singlistdemo.add(2) 93 singlistdemo.add(65) 94 singlistdemo.insert(2,77) 95 singlistdemo.insert(1,66) 96 singlistdemo.insert(0,66) 97 98 99 print(singlistdemo.length()) 100 singlistdemo.travel() 101 singlistdemo.remove(1) 102 singlistdemo.travel() 103 singlistdemo.search(65)