1 #!/usr/bin/env python 2 3 class Node(object): 4 def __init__(self,elem,next_=None): 5 self.elem = elem 6 self.next = next_ 7 8 class Simple_List(object): 9 def __init__(self): 10 self.head = None 11 12 def is_empty(self): 13 return self.head == None 14 15 def prepend(self,elem): 16 self.head = Node(elem, self.head) 17 18 def prepop(self): 19 if self.is_empty(): 20 raise ValueError("list is empty") 21 e = self.head.elem 22 self.head = self.head.next 23 return e 24 25 def find_the_key(sl,key): 26 if key < 0: 27 raise ValueError("key must >= 0") 28 i,j = sl.head,sl.head 29 while key: 30 j = j.next 31 if j is None: 32 raise ValueError("key must < list's length") 33 key -= 1 34 while j.next: 35 i,j = i.next,j.next 36 return i.elem 37 38 if __name__=="__main__": 39 sl = Simple_List() 40 for i in range(5,-1,-1): 41 sl.prepend(i) 42 print(find_the_key(sl,0))