class Node(): def __init__(self,InitDate): self.Date=InitDate self.next=None def setNext(self,newnext): self.next=newnext def setDate(self,newDate): self.Date=newDate def getNext(self): return self.next def getDate(self): return self.Date class LinkedList(): def __init__(self): self.head=None def isEmpty(self): return self.head==None def add(self,item): temp=Node(item) temp.setNext(self.head) self.head=temp def size(self): current=self.head count=0 while(current!=None): count+=1 current=current.getNext() return count def show(self): current=self.head while(current!=None): print current.getDate(), current=current.getNext() print " " def search(self,item): current=self.head found=False while not found and (current != None): if current.getDate()==item: found=True else: current=current.getNext() print found def remove(self,item): previous=None current=self.head found=False while not found and (current != None): if current.getDate()==item: found=True else: previous=current current=current.getNext() if found==False: print "not {0}".format(item) elif current==self.head: self.head=current.getNext() else: previous.setNext(current.getNext()) def insert(self,index,item): previous=None current=self.head count=0 temp=Node(item) if index>self.size(): print "out index" elif index==0: temp.setNext(current) self.head=temp else: while index: index-=1 previous=current current=current.getNext() previous.setNext(temp) temp.setNext(current) if __name__=="__main__": alist=LinkedList() for i in range(10): alist.add(i) alist.show() print alist.size() alist.remove(5) alist.show() alist.insert(7,110) alist.show() alist.search(110)
输出:
9 8 7 6 5 4 3 2 1 0
10
9 8 7 6 4 3 2 1 0
9 8 7 6 4 3 2 110 1 0
True