Download Lecture Slides - Department of Computer Science

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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


Reference:

2
Chapter 3 – The Ordered List Abstract Data Type
http://www.bogotobogo.com/python/python_iterators.php
COMPSCI105
10
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
3
Ordered
COMPSCI105
10
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
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
4
COMPSCI105
10
18.2 The OrderedList
The OrderedList ADT






5
Constructor
is_empty()
size()
remove()
add()
search()
Same as those of
UnorderedList
Different!
COMPSCI105
10
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.


add(item) adds a new item to the list.


It needs no parameters and returns a boolean value.
No checking is
done in the
implementation!
size() returns the number of items in the list.

6
It needs the item and returns a boolean value.
is_empty() tests to see whether the list is empty.


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 nothing. Assume the item is not already in
the list.
remove(item) removes the item from the list.


It needs no parameters and returns an empty list.
It needs no parameters and returns an integer.
COMPSCI105
17
18.3 Operations
Inserting a Node (Review)

UnorderedList

Only insert new item at the beginning of a linked list
new_node = Node(item)


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
new_node.set_next(self.head)
self.head = new_node
7
2
COMPSCI105
1
10
18.3 Operations
Inserting a Node - OrderedList

OrderedList

Create a new node and store the new data in it
new_node = Node(item)
Must determine the
point of insertion

Determine the point of insertion


Insert at the beginning of a linked list, OR
Insert at the middle of a linked list


8
Use the prev reference
Connect the new node to the linked list by changing references
COMPSCI105
10
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)
17 < 49
26 < 49
31 < 49
54 > 49
previous previous previous
9
COMPSCI105
Integers are in
ascending order
10
18.3 Operations
Inserting a Node - OrderedList

Insert at the beginning of a linked list
1
2
new_node.set_next(self.head)
self.head = new_node

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
2
1
new_node.set_next(current)
previous.set_next(new_node)
10
COMPSCI105
10
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
11
COMPSCI105
10
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
12
COMPSCI105
10
18.3 Operations
UnorderedList Vs OrderedList
13
UnorderedList
OrderedList
is_empty
O(1)
O(1)
size
O(1) with count variable
O(1) with count variable
add
O(1)
O(n)
remove
O(n)
O(n)
search
O(n)
O(n)
COMPSCI105
10
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.

14
It is useful to be able to traverse an UnorderedList or an OrderedList, i.e.,
visit each element exactly once.
COMPSCI105
10
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:
1
2
3
for item in num_list:
print(item)

The list object supports the iterator protocol.

To explicitly create an iterator, use the built-in iter function:
i = iter(num_list)
print(next(i)) # fetch first value
print(next(i))
15
COMPSCI105
1
2
10
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
16
COMPSCI105
10
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
17
COMPSCI105
Raise this error to tell
consumer to stop
10
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.
for num in my_linked_list:
print(num, end=" ")

However, we will get the following error:
for num in my_linked_list:
TypeError: 'UnorderedList' object is not iterable

Solution:


18
Create an iterator class for the linked list.
Add the __iter()__ method to return an instance of the
LinkedListIterator class.
COMPSCI105
10
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
19
COMPSCI105
10
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)
20
COMPSCI105
10