200 likes | 314 Views
COMPSCI 105 S2 2014 Principles of Computer Science. Linked Lists 2. Agenda & Reading. Agenda Introduction The OrderedList Operations Iterators Linked List Iterators Extra Reading Textbook: Problem Solving with Algorithms and Data Structures
E N D
COMPSCI 105 S2 2014Principles of Computer Science Linked Lists 2
Agenda & Reading • Agenda • Introduction • The OrderedList • Operations • Iterators • Linked List Iterators • Extra Reading • Textbook: • Problem Solving with Algorithms and Data Structures • Chapter 3 – The Ordered List Abstract Data Type • Reference: • http://www.bogotobogo.com/python/python_iterators.php COMPSCI105
18.1 Introduction Unordered Vs Ordered • A list is a collection of items where each item holds a relative position with respect to the others. • It must maintain a reference to the first node (head) • It is commonly known as a linked list • Unordered Vs Ordered • Unordered meaning that the items are not stored in a sorted fashion. 54, 26, 93, 17, 77 and 31 17, 26, 31, 54, 77 and 93 Unordered Ordered COMPSCI105
18.2 The OrderedList The OrderedList • The structure of an ordered list is a collection of items where each item holds a relative position that is basedupon some underlying characteristic of the item. • i.e. either ascending or descending my_orderedlist = OrderedList() num_list = [77, 17, 26, 31, 93, 54] for num in num_list: my_orderedlist.add(num) Integers are in ascending order COMPSCI105
18.2 The OrderedListThe OrderedList ADT • Constructor • is_empty() • size() • remove() • add() • search() Same as those of UnorderedList Different! COMPSCI105
18.2 The OrderedList The OrderedList Abstract Data Type • What are the operations which can be used with an OrderedList Abstract Data? • creates a new list that is empty. • It needs no parameters and returns an empty list. • add(item) adds a new item to the list. • It needs the item and returns nothing. Assume the item is not already in the list. • remove(item) removes the item from the list. • It needs the item and modifies the list. Assume the item is presentin the list. • search(item) searches for the item in the list. • It needs the item and returns a boolean value. • is_empty() tests to see whether the list is empty. • It needs no parameters and returnsa boolean value. • size() returns the number of items in the list. • It needs no parameters and returnsan integer. No checking is done in the implementation! COMPSCI105
18.3 OperationsInserting a Node (Review) • UnorderedList • Only insert new item at the beginning of a linked list • Create a new Node and store the new data into it • Connect the new node to the linked list by changing references • change the next reference of the new node to refer to the old first node of the list • modify the head of the list to refer to the new node 1 2 new_node = Node(item) new_node.set_next(self.head) self.head = new_node COMPSCI105
18.3 Operations Inserting a Node - OrderedList • OrderedList • Create a new node and store the new data in it • Determine the point of insertion • Insert at the beginning of a linked list, OR • Insert at the middle of a linked list • Use the prev reference • Connect the new node to the linked list by changing references new_node = Node(item) Must determine the point of insertion COMPSCI105
18.3 Operations Determine the point of insertion • Starting point: • current = self.head • previous = None • stop = False while current != None and not stop: if current.get_data() > item: stop = True else: previous = current current = current.get_next() my_orderedlist.add(49) 31 < 49 54 > 49 26 < 49 17 < 49 Integers are in ascending order previous previous previous COMPSCI105
18.3 Operations Inserting a Node - OrderedList • Insert at the beginning of a linked list • Insert at the middle of a linked list • change the next reference of the new node to refer to the current node of the list • modify the next reference of the prev node to refer to the new node 1 2 new_node.set_next(self.head) self.head = new_node 2 1 new_node.set_next(current) previous.set_next(new_node) COMPSCI105
18.3 Operations Searching an Item • Searches for the item in the list. Returns a Boolean. • Examples: print (my_linked_list.search(31)) True current print (my_linked_list.search(39)) False current COMPSCI105
18.3 Operations Searching an item • To search an item in a linked list: • set a pointer to be the same address as head, • process the data in the node, (search) • move the pointer to the next node, and so on. • Loop stops either 1) found the item, or 2) when the next pointer is None, or 3) value in the node is greater than the item that we are searching current = self.head while current != None: if current.get_data() == item: return True elif current.get_data() > item: return False else: current = current.get_next() return False COMPSCI105
18.3 Operations UnorderedList Vs OrderedList COMPSCI105
18.4 IteratorsIterators • Traversals are very common operations, especially on containers. • Python’s for loop allows programmer to traverse items in strings, lists, tuples, and dictionaries: • Python compiler translates for loop to code that uses a special type of object called an iterator • An iterator guarantees that each element is visited exactly once. • It is useful to be able to traverse an UnorderedList or an OrderedList, i.e., visit each element exactly once. COMPSCI105
18.4 Iterators An Example: Python List Traversals • All of Python's standard built-in sequence types support iteration • The for-in statement makes it easy to loop over the items in a list: • The list object supports the iterator protocol. • To explicitly create an iterator, use the built-in iter function: for item in num_list: print(item) 1 2 3 1 2 i = iter(num_list) print(next(i)) # fetch first value print(next(i)) COMPSCI105
18.4 Iterators Create your own Iterator • You can create your own iterators if you write a function to generate the next item. You need to add: • Constructor • The __iter__() method, which must return the iterator object, and • the __next__() method, which returns the next element from a sequence. • For example: my_iterator = NumberIterator(11, 20) for num in my_iterator: print(num, end=" ") 11 12 13 14 15 16 17 18 19 20 COMPSCI105
18.4 Iterators The NumberIterator Class • Constructor, __iter__(), __next__ class NumberIterator: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def __next__(self): if self.current > self.high: raise StopIteration else: self.current += 1 return self.current - 1 Raise this error to tellconsumer to stop COMPSCI105
18.5 Linked List Iterators Linked List Traversals • Now, we would like to traverse an UnorderedList or an OrderedList using a for-loop, i.e., visit each element exactly once. • However, we will get the following error: • Solution: • Create an iterator class for the linked list. • Add the __iter()__ method to return an instance of the LinkedListIteratorclass. for num in my_linked_list: print(num, end=" ") for num in my_linked_list: TypeError: 'UnorderedList' object is not iterable COMPSCI105
18.5 Linked List Iterators The LinkedListIterator • The UnorderedList class: class UnorderedList: ... def __iter__(self): return LinkedListIterator(self.head) class LinkedListIterator: def __init__( self, head): self.current = head def __next__( self ): if self.current != None: item = self.current.get_data() self.current = self.current.get_next() return item else : raise StopIteration COMPSCI105
Exercise • What is the content inside the UnorderedList and OrderedList after executing the following code fragment? name_list = ["Gill", "Tom", "Eduardo", "Raffaele", "Serena", "Bella"] my_unorderedlist = UnorderedList() for name in name_list: my_unorderedlist.add(name) my_orderedlist = OrderedList() for name in name_list: my_orderedlist.add(name) COMPSCI105