SlideShare une entreprise Scribd logo
1  sur  29
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
1
Lists
Chapter 6
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
2
Chapter Contents
6.1 List as an ADT
6.2 An Array-Based Implementation of Lists
6.3 An array Based Implementation of Lists with
Dynamic Allocation
6.4 Introduction to Linked Lists
6.5 A Pointer-Based Implementation of Linked Lists in
C++
6.6 An Array-Based Implementation of Linked Lists
optional)
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
3
Chapter Objectives
• To study list as an ADT
• Build a static-array-based implementation of lists
and note strengths, weaknesses
• Build a dynamic-array-based implementation of
lists, noting strengths and weaknesses
– See need for destructor, copy constructor, assignment
methods
• Take first look at linked lists, note strengths,
weaknesses
• Study pointer-based implementation of linked lists
• (Optional) Study array-based implementation of
linked lists
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
4
Consider Every Day Lists
• Groceries to be purchased
• Job to-do list
• List of assignments for a course
• Dean's list
• Can you name some others??
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
5
Properties of Lists
• Can have a single element
• Can have no elements
• There can be lists of lists
• We will look at the list as an abstract data
type
– Homogeneous
– Finite length
– Sequential elements
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
6
Basic Operations
• Construct an empty list
• Determine whether or not empty
• Insert an element into the list
• Delete an element from the list
• Traverse (iterate through) the list to
– Modify
– Output
– Search for a specific value
– Copy or save
– Rearrange
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
7
Designing a List Class
• Should contain at least the following function
members
– Constructor
– empty()
– insert()
– delete()
– display()
• Implementation involves
– Defining data members
– Defining function members from design phase
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
8
Array-Based Implementation
of Lists
• An array is a viable choice for storing list elements
– Element are sequential
– It is a commonly available data type
– Algorithm development is easy
• Normally sequential orderings of list elements
match with array elements
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
9
Implementing Operations
• Constructor
– Static array allocated at compile time
• Empty
– Check if size == 1
• Traverse
– Use a loop from 0th
element to size – 1
• Insert
– Shift elements to
right of insertion point
• Delete
– Shift elements back
Also adjust
size up or
down
Also adjust
size up or
down
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
10
List Class with Static Array
• Must deal with issue of declaration of
CAPACITY
• Use typedef mechanism
typedef Some_Specific_Type ElementType
ElementType array[CAPACITY];
• For specific implementation of our class we
simply fill in desired type for
Some_Specific_Type
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
11
List Class with Static Array
• Can put typedef declaration inside or
outside of class
– Inside: must specify List::ElementType
for reference to the type outside the class
– Outside: now able to use the template
mechanism (this will be our choice)
• Also specify the CAPACITY as a const
– Also choose to declare outside class
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
12
List Class with Static Array -
Problems
• Stuck with "one size fits all"
– Could be wasting space
– Could run out of space
• Better to have instantiation of specific list
specify what the capacity should be
• Thus we consider creating a List class with
dynamically-allocated array
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
13
Dynamic-Allocation for List Class
• Changes required in data members
– Eliminate const declaration for CAPACITY
– Add variable data member to store capacity specified by
client program
– Change array data member to a pointer
– Constructor requires considerable change
• Little or no changes required for
– empty()
– display()
– erase()
– insert()
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
14
Dynamic-Allocation for List Class
• Now possible to specify different sized lists
cin >> maxListSize;
List aList1 (maxListSize);
List aList2 (500);
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
15
New Functions Needed
• Destructor
– When class object goes out of scope the pointer
to the dynamically allocated memory is
reclaimed automatically
– The dynamically allocated memory is not
– The destructor reclaims dynamically allocated
memory
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
16
New Functions Needed
• Copy Constructor – makes a "deep copy" of an
object
– When argument passed as value parameter
– When function returns a local object
– When temporary storage of object needed
– When object initialized by another in a declaration
• If copy is not made,
observe results
(aliasing problem,
"shallow" copy)
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
17
Linked List
For the array-based implementation:
1. First element is at location 0
2. Successor of item at location i is at location
i + 1
3. End is at location size – 1
Fix:
1. Remove requirement that list elements be stored
in consecutive location.
2. But then need a "link" that connects each element
to its successor
Linked Lists !!Linked Lists !!
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
18
Linked List
• Linked list nodes contain
– Data part – stores an element of the list
– Next part – stores link/pointer to next element
(when no next element, null value)
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
19
Linked Lists Operations
• Construction: first = null_value;
• Empty: first == null_value?
• Traverse
– Initialize a variable ptr to point to first node
– Process data where ptr points
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
20
Linked Lists Operations
• Traverse (ctd)
– set ptr = ptr->next, process ptr->data
– Continue until ptr == null
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
21
Operations: Insertion
• Insertion
– To insert 20 after 17
– Need address of item before point of insertion
– predptr points to the node containing 17
– Get a new node pointed to by newptr and store 20 in it
– Set the next pointer of this new node equal to the next
pointer in its predecessor, thus making it point to its
successor.
– Reset the next pointer of its predecessor to point to this
new node
20
newptr
predptr
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
22
Operations: Insertion
• Note: insertion also works at end of list
– pointer member of new node set to null
• Insertion at the beginning of the list
– predptr must be set to first
– pointer member of newptr set to that value
– first set to value of newptr
Note: In all cases, no shifting of list
elements is required !
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
23
Operations: Deletion
• Delete node containing 22 from list.
– Suppose ptr points to the node to be deleted
– predptr points to its predecessor (the 20)
• Do a bypass operation:
– Set the next pointer in the predecessor to
point to the successor of the node to be deleted
– Deallocate the node being deleted.
predptr ptr
To free
space
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
24
Linked Lists - Advantages
• Access any item as long as external link
to first item maintained
• Insert new item without shifting
• Delete existing item without shifting
• Can expand/contract as necessary
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
25
Linked Lists - Disadvantages
• List-processing algorithms that require fast access to each
element cannot be done as efficiently with linked lists.
• Consider adding an element at the end of the list
Array Linked List
a[size++] = value; Get a new node;
set data part = value
next part = null_value
If list is empty
Set first to point to new node.
Else
Traverse list to find last node
Set next part of last node to
point to new node.This is the inefficient partThis is the inefficient part
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
26
Using C++ Pointers and Classes
• To Implement Nodes
class Node
{
public:
DataType data;
Node * next;
};
• Note: The definition of a Node is recursive
– (or self-referential)
• It uses the name Node in its definition
• The next member is defined as a pointer to a Node
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
27
Working with Nodes
• Declaring pointers
Node * ptr; or
typedef Node * NodePointer;
NodePointer ptr;
• Allocate and deallocate
ptr = new Node; delete ptr;
• Access the data and next part of node
(*ptr).data and (*ptr).next
or
ptr->data and ptr->next
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
28
Data Members for Linked-List
Implementation
• A linked list will be characterized by:
– A pointer to the first node in the list.
– Each node contains a pointer to the next node in
the list
– The last node contains a null pointer
• As a variation first may
– be a structure
– also contain a count of the elements in the list
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
29
Function Members for Linked-List
Implementation
• Constructor
– Make first a null pointer and
– set mySize to 0
• Destructor
– Nodes are dynamically allocated by new
– Default destructor will not specify the delete
– A destructor must be explicitly implemented to
do the delete
0

Contenu connexe

Tendances

Introduction to Pandas and Time Series Analysis [PyCon DE]
Introduction to Pandas and Time Series Analysis [PyCon DE]Introduction to Pandas and Time Series Analysis [PyCon DE]
Introduction to Pandas and Time Series Analysis [PyCon DE]Alexander Hendorf
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for publiciqbalphy1
 
R-programming-training-in-mumbai
R-programming-training-in-mumbaiR-programming-training-in-mumbai
R-programming-training-in-mumbaiUnmesh Baile
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesAndrew Ferlitsch
 
R programming Fundamentals
R programming  FundamentalsR programming  Fundamentals
R programming FundamentalsRagia Ibrahim
 
Exploratory data analysis using r
Exploratory data analysis using rExploratory data analysis using r
Exploratory data analysis using rTahera Shaikh
 
Algorithms on Hadoop at Last.fm
Algorithms on Hadoop at Last.fmAlgorithms on Hadoop at Last.fm
Algorithms on Hadoop at Last.fmMark Levy
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply FunctionSakthi Dasans
 
A Multidimensional Distributed Array Abstraction for PGAS (HPCC'16)
A Multidimensional Distributed Array Abstraction for PGAS (HPCC'16)A Multidimensional Distributed Array Abstraction for PGAS (HPCC'16)
A Multidimensional Distributed Array Abstraction for PGAS (HPCC'16)Menlo Systems GmbH
 
pandas - Python Data Analysis
pandas - Python Data Analysispandas - Python Data Analysis
pandas - Python Data AnalysisAndrew Henshaw
 

Tendances (19)

Introduction to Pandas and Time Series Analysis [PyCon DE]
Introduction to Pandas and Time Series Analysis [PyCon DE]Introduction to Pandas and Time Series Analysis [PyCon DE]
Introduction to Pandas and Time Series Analysis [PyCon DE]
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
 
104332 sri vidhya eng notes
104332 sri vidhya eng notes104332 sri vidhya eng notes
104332 sri vidhya eng notes
 
R-programming-training-in-mumbai
R-programming-training-in-mumbaiR-programming-training-in-mumbai
R-programming-training-in-mumbai
 
Data Analysis packages
Data Analysis packagesData Analysis packages
Data Analysis packages
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
 
R language
R languageR language
R language
 
R programming Fundamentals
R programming  FundamentalsR programming  Fundamentals
R programming Fundamentals
 
Machine Learning in R
Machine Learning in RMachine Learning in R
Machine Learning in R
 
Chapter 6 ds
Chapter 6 dsChapter 6 ds
Chapter 6 ds
 
Data Structures 01
Data Structures 01Data Structures 01
Data Structures 01
 
Exploratory data analysis using r
Exploratory data analysis using rExploratory data analysis using r
Exploratory data analysis using r
 
Algorithms on Hadoop at Last.fm
Algorithms on Hadoop at Last.fmAlgorithms on Hadoop at Last.fm
Algorithms on Hadoop at Last.fm
 
Lgm saarbrucken
Lgm saarbruckenLgm saarbrucken
Lgm saarbrucken
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function
 
A Multidimensional Distributed Array Abstraction for PGAS (HPCC'16)
A Multidimensional Distributed Array Abstraction for PGAS (HPCC'16)A Multidimensional Distributed Array Abstraction for PGAS (HPCC'16)
A Multidimensional Distributed Array Abstraction for PGAS (HPCC'16)
 
pandas - Python Data Analysis
pandas - Python Data Analysispandas - Python Data Analysis
pandas - Python Data Analysis
 

En vedette

Kuliah1 Struktur Data V1.0
Kuliah1 Struktur Data V1.0Kuliah1 Struktur Data V1.0
Kuliah1 Struktur Data V1.0Zidny Nafan
 
9781285852744 ppt ch12
9781285852744 ppt ch129781285852744 ppt ch12
9781285852744 ppt ch12Terry Yoast
 
Fundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj Sahni
Fundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj SahniFundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj Sahni
Fundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj SahniMunawar Ahmed
 
C++ OOP Implementation
C++ OOP ImplementationC++ OOP Implementation
C++ OOP ImplementationFridz Felisco
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++Nitin Jawla
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsTech
 
Data Structure
Data StructureData Structure
Data Structuresheraz1
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class StructureHadziq Fabroyir
 
stacks in algorithems and data structure
stacks in algorithems and data structurestacks in algorithems and data structure
stacks in algorithems and data structurefaran nawaz
 
4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
Design 3 2011 - Design Lecture Structures
Design 3 2011 - Design Lecture  StructuresDesign 3 2011 - Design Lecture  Structures
Design 3 2011 - Design Lecture StructuresGalala University
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++Laxman Puri
 
Chapter11 sorting algorithmsefficiency
Chapter11 sorting algorithmsefficiencyChapter11 sorting algorithmsefficiency
Chapter11 sorting algorithmsefficiencyGopi Saiteja
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental PrinciplesIntro C# Book
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTUREArchie Jamwal
 

En vedette (20)

Kuliah1 Struktur Data V1.0
Kuliah1 Struktur Data V1.0Kuliah1 Struktur Data V1.0
Kuliah1 Struktur Data V1.0
 
9781285852744 ppt ch12
9781285852744 ppt ch129781285852744 ppt ch12
9781285852744 ppt ch12
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
Fundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj Sahni
Fundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj SahniFundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj Sahni
Fundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj Sahni
 
OOP C++
OOP C++OOP C++
OOP C++
 
C++ OOP Implementation
C++ OOP ImplementationC++ OOP Implementation
C++ OOP Implementation
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Data Structure
Data StructureData Structure
Data Structure
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure
 
stacks in algorithems and data structure
stacks in algorithems and data structurestacks in algorithems and data structure
stacks in algorithems and data structure
 
Data structures
Data structuresData structures
Data structures
 
4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil
 
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
 
Design 3 2011 - Design Lecture Structures
Design 3 2011 - Design Lecture  StructuresDesign 3 2011 - Design Lecture  Structures
Design 3 2011 - Design Lecture Structures
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Chapter11 sorting algorithmsefficiency
Chapter11 sorting algorithmsefficiencyChapter11 sorting algorithmsefficiency
Chapter11 sorting algorithmsefficiency
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURE
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
 

Similaire à Lec5 (20)

Lec5
Lec5Lec5
Lec5
 
Lec3
Lec3Lec3
Lec3
 
Lec4
Lec4Lec4
Lec4
 
Tree
TreeTree
Tree
 
Tree
TreeTree
Tree
 
9781285852744 ppt ch18
9781285852744 ppt ch189781285852744 ppt ch18
9781285852744 ppt ch18
 
Unit i(dsc++)
Unit i(dsc++)Unit i(dsc++)
Unit i(dsc++)
 
Python - Lecture 12
Python - Lecture 12Python - Lecture 12
Python - Lecture 12
 
9781285852744 ppt ch08
9781285852744 ppt ch089781285852744 ppt ch08
9781285852744 ppt ch08
 
Data Structure Using C
Data Structure Using CData Structure Using C
Data Structure Using C
 
Week 1 - Data Structures and Algorithms
Week 1 - Data Structures and AlgorithmsWeek 1 - Data Structures and Algorithms
Week 1 - Data Structures and Algorithms
 
9781423902096_PPT_ch09.ppt
9781423902096_PPT_ch09.ppt9781423902096_PPT_ch09.ppt
9781423902096_PPT_ch09.ppt
 
01_intro-cpp.ppt
01_intro-cpp.ppt01_intro-cpp.ppt
01_intro-cpp.ppt
 
01_intro-cpp.ppt
01_intro-cpp.ppt01_intro-cpp.ppt
01_intro-cpp.ppt
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
 
lecture1.ppt
lecture1.pptlecture1.ppt
lecture1.ppt
 
II B.Sc IT DATA STRUCTURES.pptx
II B.Sc IT DATA STRUCTURES.pptxII B.Sc IT DATA STRUCTURES.pptx
II B.Sc IT DATA STRUCTURES.pptx
 
Lecture 9.pptx
Lecture 9.pptxLecture 9.pptx
Lecture 9.pptx
 
ADS UNIT II -Priority queue.pptx
ADS UNIT II -Priority queue.pptxADS UNIT II -Priority queue.pptx
ADS UNIT II -Priority queue.pptx
 
Introduction data structure
Introduction data structureIntroduction data structure
Introduction data structure
 

Plus de Ibrahim El-Torbany (14)

Idea2
Idea2Idea2
Idea2
 
Cpp lernaufgabe linked_list
Cpp lernaufgabe linked_listCpp lernaufgabe linked_list
Cpp lernaufgabe linked_list
 
C++ examples &revisions
C++ examples &revisionsC++ examples &revisions
C++ examples &revisions
 
Lec6 mod linked list
Lec6 mod linked listLec6 mod linked list
Lec6 mod linked list
 
Lec2
Lec2Lec2
Lec2
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
 
Lec1
Lec1Lec1
Lec1
 
Ass logic
Ass logicAss logic
Ass logic
 
Math lecture 4 Part 1
Math lecture 4 Part 1Math lecture 4 Part 1
Math lecture 4 Part 1
 
Tutorial 1
Tutorial 1Tutorial 1
Tutorial 1
 
Lec2&3_DataStructure
Lec2&3_DataStructureLec2&3_DataStructure
Lec2&3_DataStructure
 
Lecture 2 math 2
Lecture 2 math 2Lecture 2 math 2
Lecture 2 math 2
 
Lec1
Lec1Lec1
Lec1
 
Chapter 1 what is statistics
Chapter 1 what is statisticsChapter 1 what is statistics
Chapter 1 what is statistics
 

Dernier

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 

Dernier (20)

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 

Lec5

  • 1. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 1 Lists Chapter 6
  • 2. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 2 Chapter Contents 6.1 List as an ADT 6.2 An Array-Based Implementation of Lists 6.3 An array Based Implementation of Lists with Dynamic Allocation 6.4 Introduction to Linked Lists 6.5 A Pointer-Based Implementation of Linked Lists in C++ 6.6 An Array-Based Implementation of Linked Lists optional)
  • 3. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 3 Chapter Objectives • To study list as an ADT • Build a static-array-based implementation of lists and note strengths, weaknesses • Build a dynamic-array-based implementation of lists, noting strengths and weaknesses – See need for destructor, copy constructor, assignment methods • Take first look at linked lists, note strengths, weaknesses • Study pointer-based implementation of linked lists • (Optional) Study array-based implementation of linked lists
  • 4. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 4 Consider Every Day Lists • Groceries to be purchased • Job to-do list • List of assignments for a course • Dean's list • Can you name some others??
  • 5. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 5 Properties of Lists • Can have a single element • Can have no elements • There can be lists of lists • We will look at the list as an abstract data type – Homogeneous – Finite length – Sequential elements
  • 6. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 6 Basic Operations • Construct an empty list • Determine whether or not empty • Insert an element into the list • Delete an element from the list • Traverse (iterate through) the list to – Modify – Output – Search for a specific value – Copy or save – Rearrange
  • 7. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 7 Designing a List Class • Should contain at least the following function members – Constructor – empty() – insert() – delete() – display() • Implementation involves – Defining data members – Defining function members from design phase
  • 8. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 8 Array-Based Implementation of Lists • An array is a viable choice for storing list elements – Element are sequential – It is a commonly available data type – Algorithm development is easy • Normally sequential orderings of list elements match with array elements
  • 9. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 9 Implementing Operations • Constructor – Static array allocated at compile time • Empty – Check if size == 1 • Traverse – Use a loop from 0th element to size – 1 • Insert – Shift elements to right of insertion point • Delete – Shift elements back Also adjust size up or down Also adjust size up or down
  • 10. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 10 List Class with Static Array • Must deal with issue of declaration of CAPACITY • Use typedef mechanism typedef Some_Specific_Type ElementType ElementType array[CAPACITY]; • For specific implementation of our class we simply fill in desired type for Some_Specific_Type
  • 11. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 11 List Class with Static Array • Can put typedef declaration inside or outside of class – Inside: must specify List::ElementType for reference to the type outside the class – Outside: now able to use the template mechanism (this will be our choice) • Also specify the CAPACITY as a const – Also choose to declare outside class
  • 12. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 12 List Class with Static Array - Problems • Stuck with "one size fits all" – Could be wasting space – Could run out of space • Better to have instantiation of specific list specify what the capacity should be • Thus we consider creating a List class with dynamically-allocated array
  • 13. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 13 Dynamic-Allocation for List Class • Changes required in data members – Eliminate const declaration for CAPACITY – Add variable data member to store capacity specified by client program – Change array data member to a pointer – Constructor requires considerable change • Little or no changes required for – empty() – display() – erase() – insert()
  • 14. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 14 Dynamic-Allocation for List Class • Now possible to specify different sized lists cin >> maxListSize; List aList1 (maxListSize); List aList2 (500);
  • 15. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 15 New Functions Needed • Destructor – When class object goes out of scope the pointer to the dynamically allocated memory is reclaimed automatically – The dynamically allocated memory is not – The destructor reclaims dynamically allocated memory
  • 16. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 16 New Functions Needed • Copy Constructor – makes a "deep copy" of an object – When argument passed as value parameter – When function returns a local object – When temporary storage of object needed – When object initialized by another in a declaration • If copy is not made, observe results (aliasing problem, "shallow" copy)
  • 17. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 17 Linked List For the array-based implementation: 1. First element is at location 0 2. Successor of item at location i is at location i + 1 3. End is at location size – 1 Fix: 1. Remove requirement that list elements be stored in consecutive location. 2. But then need a "link" that connects each element to its successor Linked Lists !!Linked Lists !!
  • 18. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 18 Linked List • Linked list nodes contain – Data part – stores an element of the list – Next part – stores link/pointer to next element (when no next element, null value)
  • 19. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 19 Linked Lists Operations • Construction: first = null_value; • Empty: first == null_value? • Traverse – Initialize a variable ptr to point to first node – Process data where ptr points
  • 20. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 20 Linked Lists Operations • Traverse (ctd) – set ptr = ptr->next, process ptr->data – Continue until ptr == null
  • 21. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 21 Operations: Insertion • Insertion – To insert 20 after 17 – Need address of item before point of insertion – predptr points to the node containing 17 – Get a new node pointed to by newptr and store 20 in it – Set the next pointer of this new node equal to the next pointer in its predecessor, thus making it point to its successor. – Reset the next pointer of its predecessor to point to this new node 20 newptr predptr
  • 22. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 22 Operations: Insertion • Note: insertion also works at end of list – pointer member of new node set to null • Insertion at the beginning of the list – predptr must be set to first – pointer member of newptr set to that value – first set to value of newptr Note: In all cases, no shifting of list elements is required !
  • 23. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 23 Operations: Deletion • Delete node containing 22 from list. – Suppose ptr points to the node to be deleted – predptr points to its predecessor (the 20) • Do a bypass operation: – Set the next pointer in the predecessor to point to the successor of the node to be deleted – Deallocate the node being deleted. predptr ptr To free space
  • 24. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 24 Linked Lists - Advantages • Access any item as long as external link to first item maintained • Insert new item without shifting • Delete existing item without shifting • Can expand/contract as necessary
  • 25. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 25 Linked Lists - Disadvantages • List-processing algorithms that require fast access to each element cannot be done as efficiently with linked lists. • Consider adding an element at the end of the list Array Linked List a[size++] = value; Get a new node; set data part = value next part = null_value If list is empty Set first to point to new node. Else Traverse list to find last node Set next part of last node to point to new node.This is the inefficient partThis is the inefficient part
  • 26. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 26 Using C++ Pointers and Classes • To Implement Nodes class Node { public: DataType data; Node * next; }; • Note: The definition of a Node is recursive – (or self-referential) • It uses the name Node in its definition • The next member is defined as a pointer to a Node
  • 27. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 27 Working with Nodes • Declaring pointers Node * ptr; or typedef Node * NodePointer; NodePointer ptr; • Allocate and deallocate ptr = new Node; delete ptr; • Access the data and next part of node (*ptr).data and (*ptr).next or ptr->data and ptr->next
  • 28. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 28 Data Members for Linked-List Implementation • A linked list will be characterized by: – A pointer to the first node in the list. – Each node contains a pointer to the next node in the list – The last node contains a null pointer • As a variation first may – be a structure – also contain a count of the elements in the list
  • 29. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 29 Function Members for Linked-List Implementation • Constructor – Make first a null pointer and – set mySize to 0 • Destructor – Nodes are dynamically allocated by new – Default destructor will not specify the delete – A destructor must be explicitly implemented to do the delete 0