Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMPSCI 105 S2 2014 Principles of Computer Science Linked Lists 2.

Similar presentations


Presentation on theme: "COMPSCI 105 S2 2014 Principles of Computer Science Linked Lists 2."— Presentation transcript:

1 COMPSCI 105 S2 2014 Principles of Computer Science Linked Lists 2

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 http://www.bogotobogo.com/python/python_iterators.php 10COMPSCI1052

3 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. 10COMPSCI1053 54, 26, 93, 17, 77 and 31 17, 26, 31, 54, 77 and 93 Unordered Ordered

4 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 based upon some underlying characteristic of the item.  i.e. either ascending or descending 10COMPSCI1054 my_orderedlist = OrderedList() num_list = [77, 17, 26, 31, 93, 54] for num in num_list: my_orderedlist.add(num) 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

5 18.2 The OrderedList The OrderedList ADT  Constructor  is_empty()  size()  remove()  add()  search() 10COMPSCI1055 Same as those of UnorderedList Different!

6 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 present in 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 returns a boolean value.  size() returns the number of items in the list.  It needs no parameters and returns an integer. No checking is done in the implementation! 17COMPSCI1056

7 18.3 Operations Inserting 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 10COMPSCI1057 1 2 new_node.set_next(self.head) self.head = new_node new_node.set_next(self.head) self.head = new_node new_node = Node(item)

8 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 10COMPSCI1058 new_node = Node(item) Must determine the point of insertion

9 18.3 Operations Determine the point of insertion  Starting point:  current = self.head  previous = None  stop = False 10COMPSCI1059 while current != None and not stop: if current.get_data() > item: stop = True else: previous = current current = current.get_next() while current != None and not stop: if current.get_data() > item: stop = True else: previous = current current = current.get_next() Integers are in ascending order my_orderedlist.add(49) previous 26 < 49 31 < 4954 > 49 17 < 49

10 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 12 10COMPSCI10510 new_node.set_next(self.head) self.head = new_node new_node.set_next(self.head) self.head = new_node new_node.set_next(current) previous.set_next(new_node)

11 18.3 Operations Searching an Item  Searches for the item in the list. Returns a Boolean.  Examples: 10COMPSCI10511 print (my_linked_list.search(31)) print (my_linked_list.search(39)) current True False

12 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 10COMPSCI10512 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 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

13 18.3 Operations UnorderedList Vs OrderedList UnorderedListOrderedList is_emptyO(1) sizeO(1) with count variable addO(1)O(n) removeO(n) searchO(n) 10COMPSCI10513

14 18.4 Iterators Iterators  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. 10COMPSCI10514

15 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: 10COMPSCI10515 for item in num_list: print(item) for item in num_list: print(item) i = iter(num_list) print(next(i)) # fetch first value print(next(i)) i = iter(num_list) print(next(i)) # fetch first value print(next(i)) 1212 1212 123123 123123

16 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: 10COMPSCI10516 my_iterator = NumberIterator(11, 20) for num in my_iterator: print(num, end=" ") my_iterator = NumberIterator(11, 20) for num in my_iterator: print(num, end=" ") 11 12 13 14 15 16 17 18 19 20

17 18.4 Iterators The NumberIterator Class  Constructor, __iter__(), __next__ 10COMPSCI10517 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 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 tell consumer to stop

18 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 LinkedListIterator class. 10COMPSCI10518 for num in my_linked_list: print(num, end=" ") for num in my_linked_list: print(num, end=" ") for num in my_linked_list: TypeError: 'UnorderedList' object is not iterable for num in my_linked_list: TypeError: 'UnorderedList' object is not iterable

19 18.5 Linked List Iterators The LinkedListIterator  The UnorderedList class: 10COMPSCI10519 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 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 class UnorderedList:... def __iter__(self): return LinkedListIterator(self.head) class UnorderedList:... def __iter__(self): return LinkedListIterator(self.head)

20 Exercise  What is the content inside the UnorderedList and OrderedList after executing the following code fragment? 10COMPSCI10520 name_list = ["Gill", "Tom", "Eduardo", "Raffaele", "Serena", "Bella"] my_unorderedlist = UnorderedList() for name in name_list: my_unorderedlist.add(name) my_unorderedlist = UnorderedList() for name in name_list: my_unorderedlist.add(name) my_orderedlist = OrderedList() for name in name_list: my_orderedlist.add(name) my_orderedlist = OrderedList() for name in name_list: my_orderedlist.add(name)


Download ppt "COMPSCI 105 S2 2014 Principles of Computer Science Linked Lists 2."

Similar presentations


Ads by Google