Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python LinkedLists.

Similar presentations


Presentation on theme: "Python LinkedLists."— Presentation transcript:

1 Python LinkedLists

2 LinkedList Code from class on Thursday September 19, 2013
element Node size LinkedList next 1 head 1 tail 1 n1 ll1 element = “a” next = None size = 0 head = n2 tail = n1 element = “b” next = n1 n2 class LinkedList() : head = None tail = None size = 0 def cons(self, val) : n = Node(val) self.size+=1 if self.head == None : self.head = n self.tail = n else : n.next = self.head return self def car(self) : return self.head.element def cdr(self) : l = self if self.size > 0 : l.head = l.head.next l.size -= 1 return l def __str__(self): result = "'(" current = self.head for i in range(self.size+1): if current != None: result += str(current.element) if current.next != None : result += ", " # Separate two elements with a comma current = current.next else: result += ")" # Insert the closing ] in the string return result # Return an iterator for a linked list def __iter__(self): # To be discussed in Section 18.3 return LinkedListIterator(self.head) # The Node class class Node: def __init__(self, element): self.element = element self.next = None class LinkedListIterator: # To be discussed in Section 18.3 def __init__(self, head): self.current = head def next(self): if self.current == None: raise StopIteration element = self.current.element self.current = self.current.next return element ll1 = LinkedList() n1 = Node("a") ll1.head = n1 ll1.tail = n1 ll1.size+=1 print "ll1 is: ", ll1 n2 = Node("b") ll1.head = n2 n2.next = n1 Gives: ll1 is: '(a) ll1 is: '(b, a) See the class calendar for a larger font size version of this code.


Download ppt "Python LinkedLists."

Similar presentations


Ads by Google