+ All Categories
Home > Documents > COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

Date post: 05-Jan-2016
Category:
Upload: lynne-cobb
View: 215 times
Download: 1 times
Share this document with a friend
Popular Tags:
38
COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1
Transcript
Page 1: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

COMPSCI 105 SS 2015Principles of Computer Science

Linked Lists 1

Page 2: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

2

Agenda & Reading Agenda

Introduction The Node class The UnorderedList ADT Comparing Implementations The OrderedList ADT Linked List Iterators

Textbook: Problem Solving with Algorithms and Data Structures

Chapter 3 – Lists Chapter 3 - Unordered List Abstract Data Type Chapter 3 - Implementing an Unordered List: Linked Lists Chapter 3 – The OrderedList Abstract Data Type

Lecture 12COMPSCI105

Page 3: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

3

Review We have used Python lists to implement the

abstract data types presented (Stack and Queue). The list is a powerful, yet simple, collection

mechanism that provides the programmer with a wide variety of operations.

A Python list stores each element in contiguous memory if

possible. This makes it possible to access any element in O(1) time.

However, insertion or deletion elements at the beginning of the list takes O(n).

Lecture 12COMPSCI105

Page 4: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

4

1 Introduction

ADT List A list is a collection of items where each item

holds a relative position with respect to the others. We can consider the list as having a first item, a second item, a third item, and so on. We can also refer to the beginning of the list (the first item) and the end of the list (the last item).

Unordered Vs Ordered Unordered meaning that the items are not stored in a

sorted fashion.

A Python list ([]) is an implementation of an unordered list,

54, 26, 93, 17, 77 and 31 17, 26, 31, 54, 77 and 93

Lecture 12COMPSCI105

Page 5: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

5

1 Introduction

The List Abstract Data Type What are the operations which can be used with a List

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 implementati

on!

Lecture 12COMPSCI105

Page 6: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

6

1 Introduction

Contiguous Memory A Python list stores each element in contiguous

memory if possible. List ADT – there is no requirement that the items be

stored in contiguous memory In order to implement an unordered list, we will

construct what is commonly known as a linked list. A Node object will store

the data in the node of the list, and a link to the next Node object.

Lecture 12COMPSCI105

Page 7: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

7

1 Introduction

Insertion and Deletion Items can be inserted into and deleted from the

linked list without shifting data.

Lecture 12COMPSCI105

Page 8: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

8

A node is the basic building block of a linked list. contains the data as well as a link to the next

node in the list.

2 The Node class

The Node class

p = Node(93)temp = Node(93)

p

Lecture 12COMPSCI105

Page 9: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

9

2 The Node class

Definition of the Node class

class Node: def __init__(self, init_data): self.data = init_data self.next = None

def get_data(self): return self.data

def get_next(self): return self.next

def set_data(self, new_data): self.data = newdata

def set_next(self, new_next): self.next = new_next)

Lecture 12COMPSCI105

Page 10: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

10

2 The Node class

Chain of nodes You can build a chain of nodes using Node objects

n = Node(6)first = Node(9)first.set_next(n)

n.set_data(1)print(first.get_next().get_data()))

1

1

Lecture 12COMPSCI105

Page 11: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

11

Exercise 1 What is the output of the following program?

def print_chain(n): while not n == None: print(n.get_data(), end = " ") n = n.get_next()

n5 = Node(15)n6 = Node(34)n7 = Node(12)n8 = Node(84)

n6.set_next(n5)n7.set_next(n8)n8.set_next(n6)n5.set_next(None)

print_chain(n5)print()print_chain(n6)print()print_chain(n7)print()print_chain(n8)print()

Lecture 12COMPSCI105

Page 12: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

12

3 The UnorderedList class

The UnorderedList ADT The unordered list is built from a collection of

nodes, each linked to the next by explicit references. It must maintain a reference to the first node (head) It is commonly known as a linked list

Examples: An Empty List:

A linked list of integers

Lecture 12COMPSCI105

Page 13: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

13

3 The UnorderedList class

Operations List() 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 implementati

on!

Lecture 12COMPSCI105

Page 14: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

14

3 The UnorderedList class

Constructor The constructor contains

A head reference variable References the list’s first node Always exists even when the list is empty

Examples: An Empty List:

A linked list of integers

class UnorderedList:

def __init__(self): self.head = None ...

my_list = UnorderedList()

my_list = UnorderedList()for i in range(6): my_list.add(i)

12345 0

Lecture 12COMPSCI105

Page 15: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

15

3 The UnorderedList class

List Traversals To traverse a linked list, set a pointer to be the same

address as head, process the data in the node, move the pointer to the next node, and so on. Loop stops when the next pointer is None. Use a reference variable: curr

References the current node Initially references the first node (head)

To advance the current position to the next node

Loop:

curr = self.head

curr = curr.get_next()

curr = self.head while curr != None: ... curr = curr.get_next()

Lecture 12COMPSCI105

Page 16: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

16

3 The UnorderedList class

Displaying the Contents Traversing the Linked List from the Head to the

End Use a reference variable: currcurr = self.head

while curr != None: print(curr.get_data(), end=" ") curr = curr.get_next()

Print the contents of a linked list

54 25 93 17 77 31

Lecture 12COMPSCI105

Page 17: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

17

3 The UnorderedList class

is_empty() & size() is_empty()

tests to see whether the list is empty.

size() Returns the number of items in the list.

Traverses the list and counts the number of items

return self.head == None

curr = self.head count = 0while curr != None: count = count + 1 curr = curr.get_next()

count 0->1->2->3->4->5->6

Lecture 12COMPSCI105

Page 18: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

18

3 The UnorderedList class

Inserting a Node To insert 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.set_next(self.head)

new_node = Node(item)1

2

3self.head = new_node

3

Lecture 12COMPSCI105

Page 19: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

19

3 The UnorderedList class

Searching an Item Searches for the item in the list. Returns a

Boolean. Examples:

print (my_list.search(17))

print (my_list.search(1))

current

current

True

False

Lecture 12COMPSCI105

Page 20: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

20

3 The UnorderedList class

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.

curr = self.head while curr != None: if curr.get_data() == item: return True else: curr = curr.get_next()return False

Lecture 12COMPSCI105

Page 21: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

21

3 The UnorderedList class

Deleting a Node Removes the item from the list.

It needs the item and modifies the list. Assume the item is present in the list.

Examples Delete the first node

Delete a node in the middle of the list With prev and curr references

my_list.remove(5)

my_list.remove(8)

Lecture 12COMPSCI105

Page 22: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

22

To delete a node from a linked list Locate the node that you want to delete (curr) Disconnect this node from the linked list by changing

references

Two situations: To delete the first node

Modify head to refer to the node after the current node

To delete a node in the middle of the list Set next of the prev node to refer to the node after the

current node

3 The UnorderedList class

Deleting a Node

1

1

self.head = curr.get_next()

previous.set_next(curr.get_next())

prev is Nonecurr references to the first node

Lecture 12COMPSCI105

Page 23: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

23

4 Comparing Implementations

UnorderedList Version2 With a count variable to count the number of

items in the listclass UnorderedListV2:

def __init__(self): self.head = None self.count = 0

def size(self): return self.count

def is_empty(self): return self.count == 0

Big-O is O(1)

def add(self, item): new_node = Node(item) ... self.count += 1

def remove(self, item): current = self.head ... self.count -= 1

Lecture 12COMPSCI105

Page 24: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

24

4 Comparing Implementations

Comparing Implementations

Python List

UnorderedList

if len(my_plist)== 0: … O(1) is_empty O(1)

len O(1) size O(1) with count variableO(n) without count variable

append (end of the python List)insert (i, item)

O(1)O(n)

add O(1) (beginning of the linked list)

removedel

O(n)O(n)

O(n)

in O(n) search O(n)

Lecture 12COMPSCI105

Page 25: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

25

5 The OrderedList

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. 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

54, 26, 93, 17, 77 and 31

17, 26, 31, 54, 77 and 93

Unordered

Ordered

my_orderedlist = OrderedList()num_list = [77, 17, 26, 31, 93, 54]for num in num_list: my_orderedlist.add(num)

Lecture 12COMPSCI105

Page 26: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

26

5 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 implementati

on!

Lecture 12COMPSCI105

Page 27: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

27

5 The OrderedList

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()

Integers are in ascending order

my_orderedlist.add(49)

previous previousprevious

26 < 49

31 < 49

54 > 4917 <

49Must

determine the point of

insertion

Lecture 12COMPSCI105

Page 28: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

28

5 The OrderedList

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

12

12

new_node.set_next(self.head)self.head = new_node

new_node.set_next(current) previous.set_next(new_node)

Lecture 12COMPSCI105

Page 29: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

29

5 The OrderedList

Searching an Item Searches for the item in the list. Returns a

Boolean. Examples:

print (my_linked_list.search(31))

print (my_linked_list.search(39))

current

current

True

False

Lecture 12COMPSCI105

Page 30: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

30

5 The OrderedList

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 searchingcurrent = 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

STOP

Lecture 12COMPSCI105

Page 31: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

31

5 The OrderedList

UnorderedList Vs OrderedList

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)

Lecture 12COMPSCI105

Page 32: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

32

6 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. To explicitly create an iterator, use the built-in iter function:

for item in num_list: print(item)

i = iter(num_list)print(next(i)) # fetch first valueprint(next(i))

12

Lecture 12COMPSCI105

Page 33: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

33

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: 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

Lecture 12COMPSCI105

Page 34: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

34

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 else: self.current += 1 return self.current - 1

Raise this error to tellconsumer to stop

Lecture 12COMPSCI105

Page 35: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

35

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.

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.

for num in my_linked_list: print(num, end=" ")

for num in my_linked_list:TypeError: 'UnorderedList' object is not iterable

Lecture 12COMPSCI105

Page 36: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

36

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: 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)

Lecture 12COMPSCI105

Page 37: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

37

Exercise 2 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)

Lecture 12COMPSCI105

Page 38: COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.

38

Summary 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 reference-based linked list without shifting data

Lecture 12COMPSCI105


Recommended