CS 103 Unit 11. Linked Lists. Mark Redekopp

Similar documents
CS 103 Unit 11. Linked Lists. Mark Redekopp

CS 103 Unit 15. Doubly-Linked Lists and Deques. Mark Redekopp

EE 355 Unit 11b. Doubly-Linked Lists and Deques. Mark Redekopp

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

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

Chapter 17: Linked Lists

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

CSCI 104 Memory Allocation. Mark Redekopp David Kempe

18. Dynamic Data Structures I. Dynamic Memory, Addresses and Pointers, Const-Pointer Arrays, Array-based Vectors

CS 103 Unit 12 Slides

Dynamic Memory Allocation

CA341 - Comparative Programming Languages

In Java we have the keyword null, which is the value of an uninitialized reference type

BBM 201 DATA STRUCTURES

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

Chapter 17: Linked Lists

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

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

Ch. 17: Linked Lists. Introduction to Linked Lists

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

Fast Introduction to Object Oriented Programming and C++

EE 355 Unit 10. C++ STL - Vectors and Deques. Mark Redekopp

6. Pointers, Structs, and Arrays. 1. Juli 2011

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

CSCI 104 Polymorphism. Mark Redekopp David Kempe

Data Structure Series

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)

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

CS 103 Unit 13 Slides

Heap Arrays and Linked Lists. Steven R. Bagley

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

Linked Memory. Pointers Linked Lists. September 21, 2017 Cinda Heeren / Geoffrey Tien 1

Short Notes of CS201

Pointers. Developed By Ms. K.M.Sanghavi

CS201 - Introduction to Programming Glossary By

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

CS 103 Lab - Party Like A Char Star

EE 355 Unit 13 C++ STL; Iterators, Maps, Sets. Mark Redekopp

Ashish Gupta, Data JUET, Guna

Unit 14. Passing Arrays & C++ Strings

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Structured Data. CIS 15 : Spring 2007

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Singly linked lists in C.

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

CISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts)

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

1. Which of the following best describes the situation after Line 1 has been executed?

9.2 Pointer Variables. Pointer Variables CS Pointer Variables. Pointer Variables. 9.1 Getting the Address of a. Variable

EE 355 Lab 4 - Party Like A Char Star

Pointers, Dynamic Data, and Reference Types

CSCI Trees. Mark Redekopp David Kempe

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them.

Linked lists Tutorial 5b

Consider the above code. This code compiles and runs, but has an error. Can you tell what the error is?

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

Motivation was to facilitate development of systems software, especially OS development.

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

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

CMSC 341 Lecture 7 Lists

CSCI 104 C++ STL; Iterators, Maps, Sets. Mark Redekopp David Kempe

In either case, remember to delete each array that you allocate.

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

QUIZ. What is wrong with this code that uses default arguments?

The Stack, Free Store, and Global Namespace

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Dynamic Allocation of Memory

CS 31 Discussion 1A, Week 8. Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50 a.m.

Linked List using a Sentinel

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

More C++ : Vectors, Classes, Inheritance, Templates

Lecture 14: more class, C++ streams

Pointers II. Class 31

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

Unit 7. 'while' Loops

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

CS 222: Pointers and Manual Memory Management

a data type is Types

LAB #8. Last Survey, I promise!!! Please fill out this really quick survey about paired programming and information about your declared major and CS.

04-19 Discussion Notes

CA31-1K DIS. Pointers. TA: You Lu

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

MM1_ doc Page E-1 of 12 Rüdiger Siol :21

CS 103 Unit 10 Slides

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

+ Abstract Data Types

CS 103 Lab 6 - Party Like A Char Star

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

CS24 Week 3 Lecture 1

Algorithms, Data Structures, and Problem Solving

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

CSCI 104 Inheritance. Mark Redekopp David Kempe

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

malloc(), calloc(), realloc(), and free()

Spring 2008 Data Structures (CS301) LAB

Transcription:

1 CS 103 Unit 11 Linked Lists Mark Redekopp

2 NULL Pointer Just like there was a null character in ASCII = '\0' whose ue was 0 There is a NULL pointer whose ue is 0 NULL is "keyword" you can use in C/C++ that is defined to be 0 Used to represent a pointer to "nothing" Nothing ever lives at address 0 of memory so we can use it to mean "pointer to nothing" int* ptr = NULL; // ptr has 0 in it now if(ptr!= NULL){ // it's a good pointer

3 Arrays Review Arrays are contiguous pieces of memory To find a single ue, computer only needs The start address Remember the name of the array euates to the starting address (e.g. data = 120) Which element we want Provided as an index (e.g. [20]) This is all thanks to the fact that items are contiguous in memory If we know integer element i is at location 108 do we know where element i+1 is? #include<iostream> using namespace std; int main() { int data[25]; data[20] = 7; return 0; data = 100 100 104 108 112 116 120 45 31 21 04 98 73 Memory

4 Limitations of Arrays We can dynamically allocate arrays once we know their size Example: Ask the user how many items they will need, then allocate an array for that size Problem: What if the user doesn t know how many they will create or simply changes their mind Example: cout << How many numbers do you think you will input? << endl; cin >> size; int *ptr = new int[size]; What if later the user wants to input an additional number?? Could allocate a new array of size+1 and copy items over but that becomes a time sink! Main point: Arrays, whether allocated statically or dynamically (using new or malloc), cannot be resized easily later on.

5 Analogy Natural analogy when we have a set of items that can change is to create a list Write down what you know now Can add more items later (usually to the end of the list) Remove (cross off) others when done with them Can only do this with an array if you know max size of list a of time (which is sometimes fine) 1. Do CS 103 lab 2. Join ACM or IEEE 3. Play Video Games 4. Watch a movie 5. Exercise 1. Do CS 103 lab 2. Join ACM or IEEE 3. Play Video Games 4. Watch a movie 5. Exercise 6. Eat dinner

6 BFSQ Example The size of the BFSQ grew and shrunk based on the data pattern But we wasted a whole LARGE array planning for the worst case It'd be great to store only what we need where our storage can grow and shrink... # # S # # #. # F tail 5 tail 5 1 9 5 1 9 0 2 tail 5 1 9 0 2 tail

7 Linked Lists A linked list stores ues in separate chunks of memory (i.e. a dynamically allocated object) To know where the one is, each one stores a pointer to the We can allocate more or delete old ones as needed so we only use memory as needed All we do is track where the first object is (i.e. the pointer) 0x168 3 9 0x168 2 0x0 (Null)

8 Linked Lists What is the order of ues in this linked list? How would you insert 6 at the front of the list? How would you remove the ue 4? 0x300 0x240 0x200 8 0x0 (Null) 4 0x3e0 0x300 5 0x240 0x3e0 1 0x200

9 Arrays vs. Linked List If we have the start address of an array can we get the i-th element quickly? Yes: start-addr + i * sizeof(data) If we have the start () pointer to a linked list can we find the i-th element quickly? No Have to walk the linked list Linked lists trade the ability to resize (grow/shrink) for speed of access when attempting to get a specific element #include<iostream> using namespace std; int main() { int data[25]; data[20] = 7; return 0; data = 100 100 104 108 112 116 120 45 31 21 04 98 73 Memory 3 9 0x168 0x168 2 0x0 (Null)

10 Linked List Use structures/classes and pointers to make linked data structures List Arbitrarily sized collection of ues Can add any number of new ues via dynamic memory allocation Usually supports following set of operations: Append ( push_back ) Prepend ( push_front ) Remove back item ( pop_back ) Remove front item ( pop_front ) Find (look for particular ue) #include<iostream> using namespace std; struct Item { int ; Item* ; ; class List { public: List(); ~List(); void push_back(int v);... private: Item* ; ; class List: 0x0 struct Item blueprint: int Item * Rule of thumb: Still use structs for objects that are purely collections of data and don t really have operations associated with them. Use classes when data does have associated functions/methods.

11 Linked List Use structures/classes and pointers to make linked data structures List Arbitrarily sized collection of ues Can add any number of new ues via dynamic memory allocation Usually supports following set of operations: Append ( push_back ) Prepend ( push_front ) Remove back item ( pop_back ) Remove front item ( pop_front ) #include<iostream> using namespace std; List::List() { = NULL; void List::push_back(int v){ if( == NULL){ = new Item; -> = v; -> = NULL; else {... int main() { List mylist; mylist.push_back(3); 0x0 3 NULL

12 Linked List Use structures/classes and pointers to make linked data structures List Arbitrarily sized collection of ues Can add any number of new ues via dynamic memory allocation Usually supports following set of operations: Append ( push_back ) Prepend ( push_front ) Remove back item ( pop_back ) Remove front item ( pop_front ) #include<iostream> using namespace std; List::List() { = NULL; void List::push_back(int v){ if( == NULL){ = new Item; -> = v; -> = NULL; else {... int main() { List mylist; mylist.push_back(3); mylist.push_back(9); 3 NULL 9 0x0 NULL

13 Linked List #include<iostream> using namespace std; Use structures/classes and pointers to make linked data structures List Arbitrarily sized collection of ues Can add any number of new ues via dynamic memory allocation Usually supports following set of operations: Append ( push_back ) Prepend ( push_front ) Remove back item ( pop_back ) Remove front item ( pop_front ) List::List() { = NULL; void List::push_back(int v){ if( == NULL){ = new Item; -> = v; -> = NULL; else {... int main() { List mylist; mylist.push_back(3); mylist.push_back(9); mylist.push_back(2); 3 9 0x168 0x168 2 0x0 (Null)

14 Arrays Review Arrays are contiguous pieces of memory To find a single ue, computer only needs The start address Remember the name of the array euates to the starting address (e.g. data = 120) Which element we want Provided as an index (e.g. [20]) This is all thanks to the fact that items are contiguous in memory Linked list items are not contiguous Thus, linked lists have an explicit field to indicate where the item is #include<iostream> using namespace std; int main() { int data[25]; data[20] = 7; return 0; data = 100 100 104 108 112 116 120 45 31 21 04 98 73 3 Memory 9 0x168 0x168 2 0x0 (Null)

15 Common Linked Task/Mistake 1 What is the C++ code to take a step from one item to the Answer: temp = temp-> Lesson: To move a pointer to the item use: 'ptr = ptr->' 3 9 0x0 NULL temp temp Before taking step After taking step

16 Common Linked Task/Mistake 2 Why do we need a temp pointer? Why can't we just use to take a step as in: = ->; Because if we change we have no record of where the first item is Once we take a step we have "amnesia" and forget where we came from and can't retrace our steps Lesson: Don't lose your! Before taking step 3 After taking step 1c0 9 0x0 NULL

17 Common Linked Task/Mistake 3 Mistake: Many students use the following code to get a pointer to the first item: Item* temp = ->; (or first) pointer is NOT an actual ITEM struct is just a pointer It is special in that it is the only thing that is not actually holding any data it just points at the first data-filled struct -> actually points to the 2 nd item, not the 1 st because already points to the 1 st item Lesson: To get a pointer to the first item, just use '' Before taking step 3 Item* temp= -> 9 0x0 NULL temp Mistake: Thinking -> is a pointer to the first Item? Mistake: Students think is an Item

18 Common Linked Task/Mistake 4 Common errors we see is that to create a temporary pointer students also dynamically allocate an item and then immediately point it at something else causing a memory leak Item* temp = new Item; temp = ; or temp = ->; You may declare pointers w/o having to allocate anything Item* temp; Item* temp = NULL; Item* temp = ; Lesson: Only use 'new' when you really want a new Item to come alive Before taking step 0x2a0 temp 3 Mistake: Allocating an item when you declare a temporary pointer After taking step 1c0???? 9 0x0 NULL Item* temp=null; 0x00 Item* temp=; Item* temp;??? temp = ;

19 Exercises In-class exercises: monkey_traverse monkey_addstart Childs toy "Barrel of Monkeys" let's children build a chain of monkeys that can be linked arm in arm http://www.toysrus.com/graphics/tru_prod_images/barrel-of-monkeys-game----ptru1-2907042dt.jpg

20 Exercise Write an integer linked list class Download the skeleton: Go to your examples directory wget http://ee.usc.edu/~redekopp/cs103/listint.tar tar xvf ListInt.tar listint.h, listint.cpp, listint_test.cpp Examine the prototypes in listint.h (complete) Complete the functions in listint.cpp Compile and test your program the code in listint_test.cpp

21 Append Write a function to add new item to back of list Start from and iterate to end of list Copy to a temp pointer Use temp pointer to iterate through the list until we find the tail (element with field = NULL) Allocate new item and fill it in Update old tail item to point at new tail item 3 temp 0x168 9 0x0 NULL temp 0x168 2 0x0 (Null) I don t know where the list ends so I have to traverse it

22 Remove First Write a function to remove first item Copy address of first item to a temp pointer Set to point at new first item (only second item) Deallocate old first item 3 9 0x168 Before 0x168 2 0x0 (Null) 3 9 0x168 0x168 2 0x0 (Null) After

23 Other Functions Write a function to print all items in list Copy to a temp pointer then use it to iterate over the items until the pointer is NULL Print each item as you iterate Find if an item in the list (return address of struct if present or NULL) Copy to a temp pointer then use it to iterate over the items until you find an item with the desired ue or until pointer is NULL Remove item with given ue [i.e. find and remove] If found, need to change the link of the previous item to point at the item after the item found Remove VAL=9 0x168 3 9 0x168 0x168 2 0x0 (Null)

24 Comparing Performance Arrays Go to element at index I O(1) Add something to the tail (assume you have a tail index) O(1) Adding something to the front of the list after there are already n elements O(n) Linked Lists Go to element at index i O(i) Add something to the tail (assume you have only pointer and n elements in the list) O(n) Adding something to the front of the list after there are already n elements O(1)