class List_Node: # self.data # self.next # constructor def __init__(self, data): self.data = data self.next = None # Called when printing the object def __str__(self): return str(self.data) def print_linked_list_pretty(self): # self is front node of list # Takes time proportional to length of list: O(n) current=self while(current!=None): print current, "->", current = current.next print "None" def print_linked_list(L): # L is front node of list current=L while(current!=None): print current # prints current.__str__() current = current.next def print_rec(L): # Base case # Stop when we hit None if L==None: print "None" else: # Recursive case print L.data, "->", print_rec(L.next) def add(L,x): # Add new element x to front of list L # Runtime O(1) newnode = List_Node(x) # (1) newnode.next=L # (1) # L=newnode # print_rec(L) return newnode # (2) New front of list def append(L,x): # Add new element x to the end of list L ### Need to deal with case when L==None if L==None: return List_Node(x) current = L while(current.next!=None): #(1) current = current.next #(1) current.next = List_Node(x) # (2) # Create L: 'a'->'b'->'c'->'d'->None L=List_Node('a') # L: 'a' -> None L.next=List_Node('b') L.next.next=List_Node('c') L.next.next.next=List_Node('d') L.print_linked_list_pretty() print_rec(L) print_rec(None) # Create list 0->1->2->3->...->n-1->None n=20 mylist = List_Node(0) current = mylist for i in range(1,n): current.next = List_Node(i) current = current.next print_rec(mylist) mylist=add(mylist,42) print_rec(mylist) print mylist=append(mylist,100) print_rec(mylist) otherList=None otherList=append(otherList,100) print_rec(otherList)