COMPSCI 105 S Principles of Computer Science. 17 Linked List(1)

Similar documents
Agenda & Reading. COMPSCI 105 SS 2015 Principles of Computer Science

Computer Science Fundamentals 107

Algorithms in Systems Engineering ISE 172. Lecture 5. Dr. Ted Ralphs

What is an algorithm?

Linked Structures Chapter John Wiley & Sons, Data Structures and Algorithms Using Python, by Rance D. Necaise.

Linked Lists. Linked List vs Array vs Python List Singly Linked List Bag ADT Revisited Building Linked Lists

Stack. Stack theory. Stack exercises. Algolab (index.html#chapters) Out[1]: Chapter 2.2: Data Structures - Stacks and.

CMSC 341 Lecture 7 Lists

Advanced Linked Lists. Doubly Linked Lists Circular Linked Lists Multi- Linked Lists

First Name: Last Name: Q1: /10

Outline. LList: A Linked Implementation of a List ADT Iterators Links vs. Arrays In-class work. 1 Chapter 4: Linked Structures and Iterators

Queues. Queue ADT Queue Implementation Priority Queues

Linked Lists. Chapter 4

A linked list grows as data is added to it. In a linked list each item is packaged into a node.

Data Structures I: Linked Lists

Abstract Data Types Chapter 1

! A data type for which: ! An ADT may be implemented using various. ! Examples:

Ashish Gupta, Data JUET, Guna

CSI33 Data Structures

CSCA48 Term Test 1 Seminar

Linked Lists. Gaddis Ch. 17. CS 2308 :: Spring 2016 Molly O'Neil

! A data structure representing a list. ! A series of nodes chained together in sequence. ! A separate pointer (the head) points to the first

Linked Lists. Chapter 12.3 in Savitch

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix

Lecture Notes CPSC 122 (Fall 2014) Today Quiz 7 Doubly Linked Lists (Unsorted) List ADT Assignments Program 8 and Reading 6 out S.

Queues The Queue ADT. The Queue ADT is defined by the following operations: init Initialize a new empty queue.

03/31/03 Lab 7. Linked Lists

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Programming II (CS300)

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

CS 331 Fall 2017 Midterm Exam 2

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

Chapter 17: Linked Lists

Queues. October 20, 2017 Hassan Khosravi / Geoffrey Tien 1

Walk through previous lectures

Data Structures. Alice E. Fischer. Lecture 4, Fall Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall / 19

Chapter 17: Linked Lists

Computer Science First Exams Pseudocode Standard Data Structures Examples of Pseudocode

CS 331 Summer 2017 Final Exam

CSI33 Data Structures

Queues. Lesson 4. CS 32: Data Structures Dept. of Computer Science

CS2210 Data Structures and Algorithms

Data Structures and Algorithms

Introduction to Linked Data Structures

CS 234. Module 3. September 29, CS 234 Module 3 Data structures, ADTs with no order of any kind, Python review 1 / 19

Computer)Science)Fundamentals)107)) Lecture)16)Contents)

! A data structure representing a list. ! A series of dynamically allocated nodes. ! A separate pointer (the head) points to the first

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

Linked Lists. Linked List Nodes. Walls and Mirrors Chapter 5 10/25/12. A linked list is a collection of Nodes: item next -3.

16. Dynamic Data Structures

A collision is said to occur when two or more keys hash to the same index location.

CS 234. Module 3. September 19, CS 234 Module 3 Data structures, ADTs with no order of any kind, Python review 1 / 33

Linked Lists. College of Computing & Information Technology King Abdulaziz University. CPCS-204 Data Structures I

Ch. 17: Linked Lists. Introduction to Linked Lists

General Insert Operation

CMPSCI 230 Discussion 1. Virtual Box and HW0

Binary Search Tree. Revised based on textbook author s notes.

Data structure and algorithm in Python

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Assignment 2. CS 234 Fall 2018 Sandy Graham. Create()

In addition to the correct answer, you MUST show all your work in order to receive full credit.

Programming II (CS300)

CSC148H Week 3. Sadia Sharmin. May 24, /20

ECM1406:DataStructuresandTeamProject. ArrayBasedLists. Chapter 3

Linked Lists and other Dynamic Data Structures

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Linked lists. A linked list is considered a recursive data structure because it has a recursive definition.

ADTs, Arrays, Linked Lists

That means circular linked list is similar to the single linked list except that the last node points to the first node in the list.

Priority Queue ADT. Revised based on textbook author s notes.

Collection Considerations

List ADT. B/W Confirming Pages

Chapter 20: Binary Trees

Elementary Data Structures: Part 1: Arrays, Lists. CSE 2320 Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington

CSE 100: GRAPH ALGORITHMS

Introduction. Reference

Lecture 3 Linear Data Structures: Arrays, Array Lists, Stacks, Queues and Linked Lists

Specifications for the ADT List Ali list provides a way to organize data List of students List of sales List of lists

DS L9: Queues

Data Structures & Algorithms

Class 26: Linked Lists

Problem with Scanning an Infix Expression

Computer Science 9608 (Notes) Chapter: 4.1 Computational thinking and problem-solving

Cpt S 122 Data Structures. Data Structures

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

Data structure is an organization of information, usually in memory, for better algorithm efficiency.

CS532: Design and Analysis of Algorithms. Overview. Linked Lists. Data Structures Intro. Classes, Objects, and Pointers.

DATA STRUCTURE AND ALGORITHM USING PYTHON

CSC148 Week 2. Larry Zhang

CIS 190: C/C++ Programming. Linked Lists

ECE 242 Data Structures and Algorithms. Linked List I. Lecture 10. Prof.

Data structure and algorithm in Python

Review: List Implementations. CSE 143 Java. Links. A Different Strategy: Lists via Links. Linked Links. CSE143 Au List

Introduction to Data Structures and Algorithms

ECM1406. Answer Sheet Lists

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

1. Stack Implementation Using 1D Array

Programming. Lists, Stacks, Queues

Transcription:

COMPSCI 105 S1 2017 Principles of Computer Science 17 Linked List(1)

Agenda Agenda & Readings Introduction The Node class The UnorderedList ADT Comparing Implementations Reference: 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 2

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

17.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 54, 26, 93, 17, 77 and 31 17, 26, 31, 54, 77 and 93 A Python list ([]) is an implementation of an unordered list, 4

17.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, 5

17.1 Introduction ADT List What are the operations which can be used with a List Abstract Data? 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 No checking is done in the implementation 6

17.1 Introduction ADT List What are the operations which can be used with a List Abstract Data? 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 7

17.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 A Link to the next Node object 8

17.1 Introduction Insertion and Deletion Items can be inserted into and deleted from the linked list without shifting data 9

17.2 The Node Class The Node class A node is the basic building block of a linked list It contains the data as well as a link to the next node in the list p p = Node(93) temp = Node(93) 10

Code 17.2 The Node Class 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 = new_data def set_next(self, new_next): self.next = new_next 11

Code 17.2 The Node Class Chain of nodes n = Node(6) first = Node(9) first.set_next(n) n.set_data(1) print(first.get_next().get_data())) 1 1 is displayed 12

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

17.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: 14

List() 17.3 The UnorderedList Class Operations 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 No checking is done in the implementation 15

Operations 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() 17.3 The UnorderedList Class Returns the number of items in the list It needs no parameters and returns an integer 16

17.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 class UnorderedList: def init (self): self.head = None... 17

17.3 The UnorderedList Class Constructor Example: An Empty List: my_list = UnorderedList() A linked list of integers my_list = UnorderedList() for i in range(6): my_list.add(i) 5 4 3 2 1 0 18

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

17.3 The UnorderedList Class List Traversals Loop stops when the next pointer is None Use a reference variable: curr References the current node Initially references the first node (head) curr = self.head To advance the current position to the next node curr = curr.get_next() Loop: curr = self.head while curr!= None:... curr = curr.get_next() 20

17.3 The UnorderedList Class Displaying the Contents Traversing the Linked List from the Head to the End Use a reference variable: curr Print the content of a linked list curr = self.head while curr!= None: print(curr.get_data(), end=" ") curr = curr.get_next() 54 25 93 17 77 31 21

is_empty() & size() is_empty() Tests to see whether the list is empty size() 17.3 The UnorderedList Class return self.head == None Returns the number of items in the list Traverses the list and counts the number of items curr = self.head count = 0 while curr!= None: count = count + 1 curr = curr.get_next() 0 1 2 3 4 5 6 22

17.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 3 new_node = Node(item) new_node.set_next(self.head) self.head = new_node 3 2 1 23

17.3 The UnorderedList Class Searching an Item Searches for the item in the list Returns a Boolean Examples: print (my_list.search(17)) True current print (my_list.search(1)) False current 24

17.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 The item is found 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 25

17.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 my_list.remove(5) Delete a node in the middle of the list With prev and curr references my_list.remove(8) 26

17.3 The UnorderedList Class Deleting a Node 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: self.head = curr.get_next() 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 previous.set_next(curr.get_next()) 27

17.3 The UnorderedList Class Example Example: def TestUnorderedList(): my_list = UnorderedList() number_list = [31, 77, 17, 93, 26, 54] for num in number_list: my_list.add(num) print (my_list.size()) print (my_list.search(17)) print (my_list.search(1)) my_list.remove(31) my_list.remove(54) print (my_list.size()) 6 True False 2 28

Exercise 2 What is the output of the following program? def TestUnorderedList(): my_list = UnorderedList() number_list = [11, 17, 7, 3, 26, 54, 2] for num in number_list: my_list.add(num) print (my_list.size()) print (my_list.search(17)) print (my_list.search(1)) my_list.remove(2) my_list.remove(54) print (my_list.size()) 29

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 referencebased linked list without shifting data 30