class Node(object): def __init__(self,data): self.data=data self.next=None class List(object): def __init__(self,node=None): self.__head=node def is_empty(self): if self.__head: return 1 else: return 0 def travel(self): p = self.__head while p != None: print(p.data,end=' ') p = p.next def length(self): p=self.__head ans=0 while p!=None: ans+=1 p=p.next return ans def add(self,item): node = Node(item) p=self.__head if not self.is_empty(): self.__head=node else: node.next=p self.__head=node def append(self,item): node= Node(item) p=self.__head if not self.is_empty(): self.add(item) else: while p.next: p=p.next p.next=node def remove(self,item): cru=self.__head pre=None while cru!=None: if cru.data==item: if pre==None: self.__head=cru.next else: pre.next=cru.next break else: pre=cru cru=cru.next def insert(self,ind,item): p=self.__head if ind==0: self.add(item) else: count=0 while count<ind-1: if p==None: return -1 p=p.next count+=1 if p.next==None: self.append(item) else: node = Node(item) node.next=p.next p.next=node def serch(self,i): p=self.__head count=0 while p!=None: if i==p.data: print(count) break p=p.next count+=1 if not p: print(-1) if __name__=='__main__': l=List() l.append(8) l.insert(0,1) l.insert(1,3) l.travel() l.remove(1) l.travel()
基于py的单链表实现
最新推荐文章于 2024-07-17 17:25:16 发布