单链表(Python)
链表——增删改查
class Node(): def __init__(self, item): self.item = item self.next = None class Link(): def __init__(self): #构造一个空链表 #head存储只能是空或者第一个节点的地址 self._head = None #头插 def add(self, item): #创建一个新的结点 node = Node(item) node.next = self._head self._head = node #遍历 def travel(self): #_head在链表创建好后一定不可变 if self.isEmpty(): print("空链表") return cur = self._head while cur: print(cur.item) cur = cur.next def isEmpty(self): return self._head == None def size(self): cur = self._head count = 0 while cur: count += 1 cur = cur.next return count def append(self, item): node = Node(item) if self._head == None: self._head = node return cur = self._head pre = None while cur: pre = cur cur = cur.next pre.next = node def search(self,item): flag = False cur = self._head while cur: if cur.item == item: flag = True break cur = cur.next return flag def insert(self,pos,item): node = Node(item) pre = None cur = self._head for i in range(pos): pre = cur cur = cur.next pre.next = node node.next = cur def remove(self,item): cur = self._head pre = None if cur.item == item: self._head = cur.next return while cur: pre = cur cur = cur.next if cur.item == item: pre.next = cur.next return link1= Link() link1.travel() link1.append(1) link1.append(3) link1.append(4) link1.travel() print(link1.search(3)) print(link1.search(4)) link1.insert(1, 2) link1.remove(4) link1.travel() # 空链表 # 1 # 3 # 4 # True # True # 1 # 2 # 3
相关推荐
koushr 2020-11-12
范范 2020-10-28
zhaochen00 2020-10-13
Mars的自语 2020-09-27
steeven 2020-09-18
kka 2020-09-14
qiangde 2020-09-13
聚沙成塔积水成渊 2020-08-16
earthhouge 2020-08-15
aanndd 2020-08-12
范范 2020-07-30
bluetears 2020-07-28
mingyunxiaohai 2020-07-19
horizonheart 2020-07-19
liushall 2020-07-18
bluetears 2020-07-05
fengshantao 2020-07-02
liuweixiao0 2020-06-27