Download 1 slide per sheet - 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

Lattice model (finance) wikipedia , lookup

Quadtree wikipedia , lookup

Interval tree wikipedia , lookup

B-tree wikipedia , lookup

Binary search tree wikipedia , lookup

Linked list wikipedia , lookup

Transcript
COMPSCI 105 S2 2016
Principles of Computer Science
Linked Lists 2
Agenda & Reading

Agenda





Introduction
The OrderedList ADT
Operations
Linked List Iterators
Textbook:

Problem Solving with Algorithms and Data Structures


Reference:

2
Chapter 3 – The OrderedList Abstract Data Type
http://www.bogotobogo.com/python/python_iterators.php
COMPSCI 105
Lecture 20
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.
17, 26, 31, 54, 77 and 93
54, 26, 93, 17, 77 and 31
Unordered
3
Ordered
COMPSCI 105
Lecture 20
The Ordered List

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)
4
COMPSCI 105
Lecture 20
The OrderedList ADT






5
Constructor
is_empty()
size()
remove()
add()
search()
COMPSCI 105
Lecture 20
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.
COMPSCI 105
Lecture 20
Inserting a Node - OrderedList

OrderedList

Create a new node and store the new data in it
Must
determine
the point of
insertion
new_node = Node(item)

Determine the point of insertion


Insert at the beginning of a linked list, OR
Insert at the middle of a linked list


7
Use the prev reference
Connect the new node to the linked list by changing references
COMPSCI 105
Lecture 20
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
8
COMPSCI 105
Integers are in
ascending order
Lecture 20

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)
9
COMPSCI 105
Lecture 20
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
10
COMPSCI 105
Lecture 20
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
STOP
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
11
COMPSCI 105
Lecture 20
5 The OrderedList
UnorderedList Vs OrderedList
12
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)
COMPSCI 105
Lecture 20
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 translates a for loop to code that uses a special type of object
called an iterator

An iterator guarantees that each element is visited exactly once.

13
It is useful to be able to traverse an UnorderedList or an OrderedList, i.e.,
visit each element exactly once.
COMPSCI 105
Lecture 20
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
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))
14
COMPSCI 105
1
2
Lecture 20
6 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:



15
Constructor
The __iter__() function, which must return the iterator object, and
the __next__() function, which returns the next element from a
sequence.
COMPSCI 105
Lecture 20
6 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
Raise this error to stop
else:
self.__current += 1
return self.__current - 1
my_iterator = NumberIterator(11, 20)
for num in my_iterator:
print(num, end=" ")
16
11 12 13 14 15 16 17 18 19 20
COMPSCI 105
Lecture 20
6 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:


17
Create an iterator class for the linked list.
Add the __iter__() function to return an instance of the
LinkedListIterator class.
COMPSCI 105
Lecture 20
6 Linked List Iterators
The LinkedListIterator
The UnorderedList class:

class LinkedListIterator:
def __init__( self, head):
self.__current = head
def __next__( self ):
if self.__current == None:
raise StopIteration
else:
item = self.__current.get_data()
self.__current = self.__current.get_next()
return item
class UnorderedList:
...
def __iter__(self):
return LinkedListIterator(self.__head)
18
COMPSCI 105
Lecture 20
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)
for item in my_unorderedlist:
print(item, end=" ")
print()
my_orderedlist = OrderedList()
for name in name_list:
my_orderedlist.add(name)
for item in my_orderedlist:
print(item, end=" ")
print()
19
COMPSCI 105
Lecture 20
Summary




20
Reference variables can be used to implement the data
structure known as a linked list
Each reference in a linked list is a reference to the next node
in the list
Any element in a list can be accessed directly; however, you
must traverse a linked list to access a particular node
Items can be inserted into and deleted from a referencebased linked list without shifting data
COMPSCI 105
Lecture 20