RT
class Node(object): def __init__(self,val,p=0): self.Data = val self.Next = p class LinkList(object): def __init__(self): self.head = 0 def __Getitem__(self, key): if self.is_empty(): print( 'empty.') elif key <0 or key > self.getlength(): print( ' error') else: return self.Getitem(key) def __setitem__(self, key, value): if self.is_empty(): print ('empty.') elif key <0 or key > self.getlength(): print('error') else: self.delete(key) return self.insert(key) def __initlist__(self,Data): self.head = Node(Data[0]) p = self.head for i in Data[1:]: node = Node(i) p.Next = node p = p.Next def getlength (self): p = self.head length = 0 while p!=0: length+=1 p = p.Next return length def is_empty(self): if self.getlength() ==0: return True else: return False def clear(self): self.head = 0 def append(self,item): q = Node(item) if self.head ==0: self.head = q else: p = self.head while p.Next!=0: p = p.Next p.Next = q def Getitem(self,index): if self.is_empty(): print ('empty.') j = 0 p = self.head while p.Next!=0 and j <index: p = p.Next j+=1 if j ==index: return p.Data else: print ('not exist!') def insert(self,index,item): if self.is_empty() or index<0 or index >self.getlength(): print ('empty.') if index ==0: q = Node(item,self.head) self.head = q p = self.head post = self.head j = 0 while p.Next!=0 and j<index: post = p p = p.Next j+=1 if index ==j: q = Node(item,p) post.Next = q q.Next = p def delete(self,index): if self.is_empty() or index<0 or index >self.getlength(): print ('empty.') if index ==0: q = Node(item,self.head) self.head = q p = self.head post = self.head j = 0 while p.Next!=0 and j<index: post = p p = p.Next j+=1 if index ==j: post.Next = p.Next def index(self,value): if self.is_empty(): print ('Linklist is empty.') p = self.head i = 0 while p.Next!=0 and not p.Data ==value: p = p.Next i+=1 if p.Data == value: return i else: return -1