class List_Node: # self.data # self.next # constructor # O(1) time def __init__(self, data): self.data = data self.next = None # Called when printing the object # O(1) time 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 # O(n) runtime current=L while(current!=None): print current # prints current.__str__() current = current.next def print_rec(L): # Runtime O(n) # 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 # Runtime proportional to length of list: O(n) ### 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) return L # nothing has changed def list_search(L,x): # Runtime: O(n) for worst-case input current = L while current!=None: if current.data==x: return current current=current.next return None def list_remove(L,x): # Removes item x from list # Runtime O(n) in the worst-case # Special case for first element if L.data==x: L = L.next # Updating front reference return L prev = L current = L.next while current!=None and current.data!=x: prev=current current=current.next # Remove node with data element x if current!=None and current.data==x: # if current.data==x: prev.next = current.next return L # Nothing has changed, but need to return something def list_remove2(L,x): # Removes item x from list # Runtime O(n) in the worst-case # Special case for first element if L.data==x: L = L.next # Updating front reference else: # Rest of list prev = L current = L.next while current!=None and current.data!=x: prev=current current=current.next # Remove node with data element x if current!=None and current.data==x: # if current.data==x: prev.next = current.next return L # Nothing has changed, but need to return something # 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) print mylist = list_remove(mylist,5) print "After removing 5:" print_rec(mylist) print mylist = list_remove(mylist,0) print "After removing 0:" print_rec(mylist)