CMSC 341 Lecture 7 Lists

Similar documents
Linked List using a Sentinel

Data Structures and Algorithms

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

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

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

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

CMSC 341 Lecture 10 Binary Search Trees

CMSC201 Computer Science I for Majors

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

CMSC201 Computer Science I for Majors

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

LINKED LISTS cs2420 Introduction to Algorithms and Data Structures Spring 2015

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

Programming II (CS300)

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Ashish Gupta, Data JUET, Guna

CS32 Discussion Sec.on 1B Week 2. TA: Zhou Ren

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

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

Data Structures and Algorithms for Engineers

Name: I. 20 II. 20 III. 20 IV. 40. CMSC 341 Section 01 Fall 2016 Data Structures Exam 1. Instructions: 1. This is a closed-book, closed-notes exam.

CpSc212 Goddard Notes Chapter 10. Linked Lists

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Linked lists. Comp Sci 1575 Data Structures. Definitions. Memory structure. Implementation. Operations. Comparison

Data Structures and Algorithms

LAB 5, THE HIDDEN DELIGHTS OF LINKED LISTS

// Pointer to the first thing in the list

1 Deletion in singly linked lists (cont d) 1 Other Functions. 1 Doubly Linked Lists. 1 Circular lists. 1 Linked lists vs. arrays

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

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

Introduction to Computer Science Midterm 3 Fall, Points

! Determine if a number is odd or even. ! Determine if a number/character is in a range. ! Assign a category based on ranges (wind speed)

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

CSE 333 Midterm Exam Cinco de Mayo, 2017 (May 5) Name UW ID#

CS 103 Unit 11. Linked Lists. Mark Redekopp

BBM 201 DATA STRUCTURES

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues

4.1 Ordered Lists Revisited

Programming II (CS300)

CS 455 Final Exam Fall 2012 [Bono] Dec. 17, 2012

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

Dynamic Data Structures

+ Abstract Data Types

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

Introduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms

CA341 - Comparative Programming Languages

CSCE 110 PROGRAMMING FUNDAMENTALS

Assignment of Objects

Data Structures and Algorithms for Engineers

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

CSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1

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

CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course

Model Solutions. COMP 103: Test May, 2013

Cpt S 122 Data Structures. Data Structures

CMSC 341 Lecture 14: Priority Queues, Heaps

CS427 Inheritance and Virtual Functions. Linked lists. 2/27. 01Replacement.cpp link! i n t GetY ( void ) { return ( y ) ; } ;

Midterm Review. CS 211 Fall 2018

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

CS250 Final Review Questions

Intro. Classes Beginning Objected Oriented Programming. CIS 15 : Spring 2007

CS 311 Data Structures and Algorithms, Spring 2009 Midterm Exam Solutions. The Midterm Exam was given in class on Wednesday, March 18, 2009.

Variables, Memory and Pointers

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Summer I Instructions:

CS250 Final Review Questions

CMSC 202H. Classes and Objects: Reusing Classes with Composition

CS250 Final Review Questions

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

Announcements. Prelude (2) Prelude (1) Data Structures and Information Systems Part 1: Data Structures. Lecture 6: Lists.

16. Dynamic Data Structures

(More) Fun with Pointers and Linked Lists! CS 16: Solving Problems with Computers I Lecture #17

Data Structures & Algorithms

CS 206 Introduction to Computer Science II

Midterm Exam 2 CS 455, Spring 2011

Introduction to Computer Science II CS S-20 Linked Lists III

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination

Section 1: True / False (2 points each, 30 pts total)

CSE 333 Midterm Exam July 24, Name UW ID#

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

Introduction to Programming in C Department of Computer Science and Engineering

Data Structures (CS301) LAB

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

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

CMSC131. Library Classes

CS 103 Unit 11. Linked Lists. Mark Redekopp

CMSC 341. Binary Search Trees CMSC 341 BST

EECE.2160: ECE Application Programming

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

Linked Lists and other Dynamic Data Structures

Linked Lists. It s a conspiracy!

CSE 143X. Accelerated Computer Programming I/II

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase

ISY00245 Principles of Programming. Module 7

RAII and Smart Pointers. Ali Malik

CS350: Data Structures Stacks

Abstract Data Structures IB Computer Science. Content developed by Dartford Grammar School Computer Science Department

Data Structures in C. C Programming and Software Tools. N.C. State Department of Computer Science

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

Transcription:

CMSC 341 Lecture 7 Lists

Today s Topics Linked Lists vs Arrays Nodes Using Linked Lists Supporting Actors (member variables) Overview Creation Traversal Deletion UMBC CMSC 341 Lists 2

Linked Lists vs Arrays 3

What is a Linked List? Data structure Dynamic Allow easy insertion and deletion Uses nodes that contain Data Pointer to next node in the list UMBC CMSC 341 Lists 4

Example Linked List In these diagrams, a doublyoutlined box indicates a pointer. head tail data data data data UMBC CMSC 341 Lists 5

Why Use Linked Lists? We already have arrays! What are some disadvantages of an array? Size is fixed once created Inserting in the middle of an array takes time Deletion as well Sorting Requires a contiguous block of memory UMBC CMSC 341 Lists 6

Arrays vs Linked Lists in Memory Array location in memory Each cell is a block of memory First node of Linked List UMBC CMSC 341 Lists 7

(Dis)Advantages of Linked Lists Advantages: Change size easily and constantly Insertion and deletion can easily happen anywhere in the Linked List Only one node needs to be contiguously stored Disadvantages: Can t access by index value Requires management of memory Pointer to next node takes up more memory UMBC CMSC 341 Lists 8

Nodes 9

Nodes A node is one element of a Linked List Nodes consist of two main parts: Data stored in the node Pointer to next node in list Often represented as structs data UMBC CMSC 341 Lists 10

Code for Node Structure struct Node { }; String name; int Node *; testgrade; // constructor // accessors // mutators name testgrade can point to other nodes two options: 1. another Node 2. UMBC CMSC 341 Lists 11

Supporting Actors of Linked Lists (Member Variables) 12

Supporting Actors of a Linked List Five member variables used to create and keep track of a Linked List All five variables are private members All of them are pointers to a Node FRONT (or HEAD) points to front of list REAR (or TAIL) points to end of list INSERT used in node creation CURR (or CURSOR) used to traverse list PREVIOUS used to traverse list UMBC CMSC 341 Lists 13

The FRONT Node Pointer FRONT points to the very first node in the Linked List What if the Linked List is empty? Points to UMBC CMSC 341 Lists 14

The REAR Node Pointer REAR points to the very last item in the Linked List Useful when inserting nodes at the end What if there is only one item in the Linked List? Points to the same item as FRONT What if the Linked List is empty? Points to UMBC CMSC 341 Lists 15

The INSERT Node Pointer INSERT is used when we are creating and inserting a new node into the Linked List INSERT = new Node; We ll see an example of this soon UMBC CMSC 341 Lists 16

The CURR and PREV Node Pointers The CURR and PREV node pointers are used to traverse or travel down the length of a Linked List Why do we need two nodes to do this? UMBC CMSC 341 Lists 17

Linked List Overview 18

Example Linked List (Again) FRONT REAR name name name name testgrade testgrade testgrade testgrade CURR INSERT PREV UMBC CMSC 341 Lists 20

Important Points to Remember Last node in the Linked List points to Each node points to either another node in the Linked List, or to Only one per node FRONT and REAR point to the first and last nodes of the Linked List, respectively UMBC CMSC 341 Lists 21

Managing Memory with Linked Lists Hard part of using Linked Lists is ensuring that none of the nodes go missing Think of Linked List as a train (Or as a conga line of Kindergarteners) Must keep track of where s point to If you re not careful, nodes can get lost in memory (you have no way to find them) UMBC CMSC 341 Lists 22

Linked List Functions What functions does a Linked List class implementation require? Linked_List constructor Initialize all member variables to insert() remove() printlist() isempty() UMBC CMSC 341 Lists 23

Linked Lists Special Cases Linked Lists often need to be handled differently under specific circumstances Linked List is empty Linked List has only one element Linked List has multiple elements Changing something with the first or last node Keep this in mind when you are coding UMBC CMSC 341 Lists 24

Creation of a Linked List 25

Creation of a New Linked List Call constructor Linked_List test = new Linked_List(); What does the constructor do? // constructor definition Linked_List() { FRONT = ; REAR = ; INSERT = ; CURR = ; PREV = ; } Why are they all set to? UMBC CMSC 341 Lists 26

Current State of Linked List test FRONT REAR CURR INSERT PREV UMBC CMSC 341 Lists 27

Inserting the First Node What do we do first? Allocate space for the node, using INSERT Initialize Node s data Then what? What are the two cases we care about? void Linked_List::insert (String name, int score) { INSERT = new Node() // initialize data INSERT.setName (name); INSERT.setGrade(score); // what do we do? UMBC CMSC 341 Lists 28

Current State of Linked List test FRONT REAR Alice 88 CURR INSERT PREV UMBC CMSC 341 Lists 29

Insertion: Empty Linked List Case If the Linked List is empty, what do we do? FRONT and REAR point to the new Node What else should we do? void Linked_List::insert (String name, int score) { // previous code... if ( isempty() ) { FRONT = INSERT; REAR = INSERT; } INSERT = ; } UMBC CMSC 341 Lists 30

Current State of Linked List test FRONT REAR Let s create another new Node that we want to insert into our Linked List Alice 88 CURR INSERT Bob 91 PREV UMBC CMSC 341 Lists 31

Insertion: Non-Empty Linked List Case Now that the Linked List is not empty, how does our insert() function change? Let s trace these changes void Linked_List::insert (String name, int score) {... // previous code for empty list else { // first add it to the end of the list REAR-> = INSERT; // then update REAR to point to the new last REAR = INSERT; } // rest of code... UMBC CMSC 341 Lists 32

Current State of Linked List test FRONT REAR Alice 88 CURR INSERT Bob 91 PREV UMBC CMSC 341 Lists 33

Current State of Linked List test FRONT REAR // first add it to the end REAR-> = INSERT; Alice 88 CURR INSERT Bob 91 PREV UMBC CMSC 341 Lists 34

Current State of Linked List test FRONT REAR // first add it to the end REAR-> = INSERT; // then update REAR REAR = INSERT; Alice 88 CURR INSERT Bob 91 PREV UMBC CMSC 341 Lists 35

Final insert() Code Combine the REAR = INSERT from the if and else statements void Linked_List::insert (String name, int score) { INSERT = new Node() // initialize data INSERT.setName (name); INSERT.setGrade(score); if ( isempty() ) { } FRONT = INSERT; // update for first item } else { REAR-> = INSERT; // add to end of list } REAR = INSERT; // update end of list INSERT = ; // reset INSERT UMBC CMSC 341 Lists 36

Current State of Linked List test FRONT REAR Alice Bob 88 91 CURR INSERT PREV UMBC CMSC 341 Lists 37

Traversal of a Linked List 38

Traversing the Linked List When would we need to traverse our list? Printing out the contents Searching for a specific node Deleting a node Counting the size of the list (Better done with an updated member variable) We ll show the code for printing the list UMBC CMSC 341 Lists 39

Our Linked List Now FRONT REAR Alice Bob Eve 88 91 94 CURR INSERT PREV We added a third node to make it more interesting. UMBC CMSC 341 Lists 40

Before Traversing the Linked List What do we do first? Check to see if the Linked List is empty If it is, what should we do? Print out a message Return from the function void Linked_List::printList() { if ( isempty() ) { cout << "This list is empty!"; return; } // rest of the function UMBC CMSC 341 Lists 41

Planning out the Traversal If the Linked List is not empty, then we begin traversing the Linked List How do we start? How do we know when to stop? How do we move from one node to another? Hint: Using CURR alone will work for this Take a look at the diagram again, and think about the steps we need to take UMBC CMSC 341 Lists 42

Exercise: Traversing a Linked List FRONT REAR Alice Bob Eve 88 91 94 CURR We don t need INSERT or PREV to traverse the Linked List. UMBC CMSC 341 Lists 43

Traversing the List To control our traversal, we ll use a loop Initialization, Termination Condition, Modification 1. Set CURR to the first node in the list 2. Continue until we hit the end of the list () 3. Move from one node to another (using ) void Linked_List::printList() { // prev code (checking if empty) for (CURR = FRONT; CURR!= ; CURR = CURR->) { // print the information cout << "Name is " << CURR->getName() << endl; cout << "Grade is " << CURR->getGrade() << endl; } UMBC CMSC 341 Lists 44

Demonstration of Traversal FRONT CURR REAR Alice Bob Eve 88 91 94 for (CURR = FRONT; CURR!= ; CURR = CURR->) { UMBC CMSC 341 Lists 45

Demonstration of Traversal FRONT CURR REAR Alice Bob Eve 88 91 94 for (CURR = FRONT; CURR!= ; CURR = CURR->) { UMBC CMSC 341 Lists 46

Demonstration of Traversal FRONT CURR REAR Alice Bob Eve 88 91 94 for (CURR = FRONT; CURR!= ; CURR = CURR->) { // print information (Alice) UMBC CMSC 341 Lists 47

Demonstration of Traversal FRONT CURR REAR Alice Bob Eve 88 91 94 for (CURR = FRONT; CURR!= ; CURR = CURR->) { UMBC CMSC 341 Lists 48

Demonstration of Traversal FRONT CURR REAR Alice Bob Eve 88 91 94 for (CURR = FRONT; CURR!= ; CURR = CURR->) { UMBC CMSC 341 Lists 49

Demonstration of Traversal FRONT CURR REAR Alice Bob Eve 88 91 94 for (CURR = FRONT; CURR!= ; CURR = CURR->) { // print information (Bob) UMBC CMSC 341 Lists 50

Demonstration of Traversal FRONT CURR REAR Alice Bob Eve 88 91 94 for (CURR = FRONT; CURR!= ; CURR = CURR->) { UMBC CMSC 341 Lists 51

Demonstration of Traversal FRONT CURR REAR Alice Bob Eve 88 91 94 for (CURR = FRONT; CURR!= ; CURR = CURR->) { UMBC CMSC 341 Lists 52

Demonstration of Traversal FRONT CURR REAR Alice Bob Eve 88 91 94 for (CURR = FRONT; CURR!= ; CURR = CURR->) { // print information (Eve) UMBC CMSC 341 Lists 53

Demonstration of Traversal FRONT CURR REAR Alice Bob Eve 88 91 94 for (CURR = FRONT; CURR!= ; CURR = CURR->) { UMBC CMSC 341 Lists 54

Demonstration of Traversal FRONT CURR REAR Alice Bob Eve 88 91 94 for (CURR = FRONT; CURR!= ; CURR = CURR->) { UMBC CMSC 341 Lists 55

Demonstration of Traversal FRONT CURR REAR Alice Bob Eve 88 91 94 for (CURR = FRONT; CURR!= ; CURR = CURR->) { } // exit the loop UMBC CMSC 341 Lists 56

Deletion from a Linked List 57

Special Cases Deletion has many special cases, including Deleting the only node Deleting the last node Deleting the first node Deleting any middle node We will need to use CURR and PREV here Why? What will we use PREV for? UMBC CMSC 341 Lists 58

Exercise: Deleting from a Linked List FRONT REAR Alice Bob Eve 88 91 94 CURR PREV What steps would you take to remove Bob? And then Alice? UMBC CMSC 341 Lists 59

Traversing for Deletion We will use CURR and PREV to keep track of where we are in the Linked List We will search for the target If found, we will delete the node And update the of the node before it If not found, we will return False If we reach the end of the list () UMBC CMSC 341 Lists 60

Looking at the Code boolean Linked_List::remove(String target) { CURR = PREV = ; } for (CURR = FRONT; CURR!= ; CURR = CURR->) { if (CURR->name == target) { // WE MADE A MATCH! // here's where the deletion will happen return true; } else { PREV = CURR; // the for loop will move CURR to next node } } return false; UMBC CMSC 341 Lists 61

Deletion Code What are the three possible locations? 1. First node in the list 2. Last node in the list 3. Node in the middle of the list if (CURR->name == target) { // WE MADE A MATCH! } if (CURR == FRONT) {} // first node else if (CURR == REAR ) {} // last node else {} // middle of the list UMBC CMSC 341 Lists 62

Deletion Code Inside each conditional, you must first fix the s around the target node Then delete the target node (CURR) if (CURR->name == target) { // WE MADE A MATCH! } if (CURR == FRONT) {} // first node else if (CURR == REAR ) {} // last node else {} // middle of the list delete CURR; UMBC CMSC 341 Lists 63

Order of Deletion Operations IMPORTANT: Deleting a node is the last thing that happens Before deletion, you must update all of the other nodes that currently point to it UMBC CMSC 341 Lists 64

Deletion Case 1: First Node in Linked List 65

Deletion Case 1: First Node FRONT CURR REAR Alice Bob Eve 88 91 94 PREV if (CURR == FRONT) { FRONT = FRONT->; } UMBC CMSC 341 Lists 66

Deletion Case 1: First Node FRONT CURR REAR Alice Bob Eve 88 91 94 PREV if (CURR == FRONT) { FRONT = FRONT->; } delete CURR; UMBC CMSC 341 Lists 67

Deletion Case 1: First Node FRONT CURR REAR Bob 91 Eve 94 PREV if (CURR == FRONT) { FRONT = FRONT->; } delete CURR; UMBC CMSC 341 Lists 68

Deletion Case 2: Last Node in Linked List 69

Deletion Case 2: Last Node FRONT PREV CURR REAR Alice Bob Eve 88 91 94 else if (CURR == REAR) { PREV-> = ; } UMBC CMSC 341 Lists 70

Deletion Case 2: Last Node FRONT PREV CURR REAR Alice Bob Eve 88 91 94 else if (CURR == REAR) { PREV-> = ; REAR = PREV; } UMBC CMSC 341 Lists 71

Deletion Case 2: Last Node FRONT PREV CURR REAR Alice Bob Eve 88 91 94 else if (CURR == REAR) { PREV-> = ; REAR = PREV; } delete CURR; UMBC CMSC 341 Lists 72

Deletion Case 2: Last Node FRONT PREV CURR REAR Alice 88 Bob 91 else if (CURR == REAR) { PREV-> = ; REAR = PREV; } delete CURR; UMBC CMSC 341 Lists 73

Deletion Case 3: Node in Middle of Linked List 74

Deletion Case 3: Middle Node FRONT PREV CURR REAR Alice Bob Eve 88 91 94 else { //middle node PREV-> = CURR->; } UMBC CMSC 341 Lists 75

Deletion Case 3: Middle Node FRONT PREV CURR REAR Alice Bob Eve 88 91 94 else { //middle node PREV-> = CURR->; } delete CURR; UMBC CMSC 341 Lists 76

Deletion Case 3: Middle Node FRONT PREV CURR REAR Alice 88 Eve 94 else { //middle node PREV-> = CURR->; } delete CURR; UMBC CMSC 341 Lists 77

Special Deletion Case: Only Node in Linked List 78

Special Deletion Case: Only Node FRONT REAR Alice 88 What happens to REAR with this code? What does it point to? CURR PREV // code that currently handles this if (CURR == FRONT) { FRONT = FRONT->; } delete CURR; UMBC CMSC 341 Lists 79

Special Deletion Case: Only Node FRONT REAR Alice 88 But this memory has been freed! That s not good CURR PREV // code that currently handles this if (CURR == FRONT) { FRONT = FRONT->; } delete CURR; UMBC CMSC 341 Lists 80

Special Deletion Case: Only Node If we are removing the only node from a Linked List, we need to set both FRONT and REAR to point to // new case for last node if (CURR == FRONT && CURR == REAR) { FRONT = FRONT->; REAR = REAR->; // or FRONT = ; // REAR = ; } delete CURR; UMBC CMSC 341 Lists 81