1 Data Structures and Algorithms Pointers and Dynamic Data.
-
Upload
dina-walton -
Category
Documents
-
view
222 -
download
0
Transcript of 1 Data Structures and Algorithms Pointers and Dynamic Data.
![Page 1: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/1.jpg)
1
Data Structures and Algorithms
Pointers and Dynamic Data
![Page 2: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/2.jpg)
2
Topics• Using the Address-Of Operator &• Declaring and Using Pointer Variables• Using the Indirection (Dereference) Operator *• The NULL Pointer• Using C++ Operators new and delete• Meaning of an Inaccessible Object• Meaning of a Dangling Pointer• Use of a Class Destructor• Shallow Copy vs. Deep Copy of Class Objects• Use of a Copy Constructor
![Page 3: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/3.jpg)
3
Recall that . . .char str [ 8 ];
str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant because the value of str itself cannot be changed by assignment. It “points” to the memory location of a char.
str [0] [1] [2] [3] [4] [5] [6] [7]
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’
6000
![Page 4: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/4.jpg)
4
Addresses in Memory
• when a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is the address of the variable
int x;
float number;
char ch;
2000 2002 2006
x number ch
![Page 5: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/5.jpg)
5
Obtaining Memory Addresses
• the address of a non-array variable can be obtained by using the address-of operator &
int x;float number;char ch;
cout << “Address of x is “ << &x << endl;
cout << “Address of number is “ << &number << endl;
cout << “Address of ch is “ << &ch << endl;
![Page 6: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/6.jpg)
6
What is a pointer variable?
• A pointer variable is a variable whose value is the address of a location in memory.
• to declare a pointer variable, you must specify the type of value that the pointer will point to,for example,
int* ptr; // ptr will hold the address of an int
char* q; // q will hold the address of a char
![Page 7: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/7.jpg)
7
Using a Pointer Variable
int x; x = 12;
int* ptr; ptr = &x;
NOTE: Because ptr holds the address of x, we say that ptr “points to” x
2000
12
x
3000
2000
ptr
![Page 8: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/8.jpg)
8
2000
12
x
3000
2000
ptr
int x; x = 12;
int* ptr; ptr = &x;
cout << *ptr;
NOTE: The value pointed to by ptr is denoted by *ptr
Unary operator * is the indirection (deference) operator
![Page 9: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/9.jpg)
9
int x; x = 12;
int* ptr; ptr = &x;
*ptr = 5; // changes the value // at address ptr to 5
Using the Dereference Operator
2000
12 5
x
3000
2000
ptr
![Page 10: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/10.jpg)
10
char ch; ch = ‘A’;
char* q; q = &ch;
*q = ‘Z’; char* p; p = q; // the rhs has value 4000 // now p and q both point to ch
Another Example 4000
A Z
ch
5000 6000
4000 4000
q p
![Page 11: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/11.jpg)
11
ptr
Using a Pointer to Access the Elements of a String
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’
3000
char msg[ ] = “Hello”; ‘M’ ‘a’
3001
char* ptr; 3000
ptr = msg; // recall that msg == &msg[ 0 ]
*ptr = ‘M’ ;
ptr++; // increments the address in ptr
*ptr = ‘a’;
![Page 12: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/12.jpg)
12
int StringLength ( /* in */ const char str[ ] ) // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Precondition: str is a null-terminated string // Postcondition: FCTVAL == length of str (not counting ‘\0’) // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - { char* p ; int count = 0;
p = str;
while ( *p != ‘\0’ ) {
count++ ; p++ ; // increments the address p by sizeof char }
return count;
}
![Page 13: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/13.jpg)
Some C++ Pointer OperationsPrecedence Higher -> Select member of class pointed to
Unary: ++ -- ! * new delete Increment, Decrement, NOT, Dereference, Allocate, Deallocate
+ - Add Subtract
< <= > >= Relational operators
== != Tests for equality, inequality
Lower = Assignment
![Page 14: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/14.jpg)
Operator new Syntax
new DataType
new DataType [IntExpression]
If memory is available, in an area called the heap (or free store) new allocates the requested object or array, and returns a pointer to (address of ) the memory allocated.
Otherwise, program terminates with error message.
The dynamically allocated object exists until the delete operator destroys it.
![Page 15: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/15.jpg)
15
The NULL Pointer
• There is a pointer constant 0 called the “null pointer” denoted by NULL in header file cstddef.
• But NULL is not memory address 0.
• NOTE: It is an error to dereference a pointer whose value is NULL. Such an error may cause your program to crash, or behave erratically. It is the programmer’s job to check for this.
while (ptr != NULL) {
. . . // ok to use *ptr here
}
![Page 16: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/16.jpg)
16
3 Kinds of Program Data
• STATIC DATA: memory allocation exists throughout execution of program
static long currentSeed;
• AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function
• DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using operators new and delete
![Page 17: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/17.jpg)
17
Allocation of Memory
STATIC ALLOCATION
Static allocation is the allocation of memory space at compile time.
DYNAMIC ALLOCATION
Dynamic allocation is the allocation of memory space at run time by using operator new.
![Page 18: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/18.jpg)
18
2000
ptr
Dynamically Allocated Data
char* ptr;
ptr = new char;
*ptr = ‘B’;
cout << *ptr;
![Page 19: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/19.jpg)
19
Dynamically Allocated Data
char* ptr;
ptr = new char;
*ptr = ‘B’;
cout << *ptr;
NOTE: Dynamic data has no variable name
2000
ptr
![Page 20: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/20.jpg)
20
Dynamically Allocated Data
char* ptr;
ptr = new char;
*ptr = ‘B’;
cout << *ptr;
NOTE: Dynamic data has no variable name
2000
ptr
‘B’
![Page 21: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/21.jpg)
21
Dynamically Allocated Data
char* ptr;
ptr = new char;
*ptr = ‘B’;
cout << *ptr;
delete ptr;
2000
ptr
NOTE: delete deallocates the memory pointed to by ptr
?
![Page 22: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/22.jpg)
• Operator delete returns to the free store memory which was previously allocated at run-time by operator new.
• The object or array currently pointed to by the pointer is deallocated, and the pointer is considered unassigned.
Using Operator delete
22
![Page 23: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/23.jpg)
23
Dynamic Array Allocation
char *ptr; // ptr is a pointer variable that // can hold the address of a char
ptr = new char[ 5 ];
// dynamically, during run time, allocates // memory for a 5 character array
// and stores the base address into ptr
ptr
6000
6000
![Page 24: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/24.jpg)
24
Dynamic Array Allocation char *ptr ;
ptr = new char[ 5 ];
strcpy( ptr, “Bye” );
ptr[ 1 ] = ‘u’; // a pointer can be subscripted
cout << ptr[ 2] ;
ptr
6000
6000 ‘B’ ‘y’ ‘e’ ‘\0’ ‘u’
![Page 25: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/25.jpg)
Operator delete Syntax
delete Pointer
delete [ ] Pointer
If the value of the pointer is 0 there is no effect.
Otherwise, the object or array currently pointed to by Pointer is deallocated, and the value of Pointer is undefined. The memory is returned to the free store.
Square brackets are used with delete to deallocate a dynamically allocated array.
![Page 26: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/26.jpg)
26
Dynamic Array Deallocation char *ptr ;
ptr = new char[ 5 ];
strcpy( ptr, “Bye” );
ptr[ 1 ] = ‘u’;
delete ptr; // deallocates array pointed to by ptr // ptr itself is not deallocated // the value of ptr is undefined.
ptr
?
![Page 27: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/27.jpg)
27
int* ptr = new int; *ptr = 3;
ptr = new int; // changes value of ptr *ptr = 4;
What happens here?
3
ptr
3
ptr
4
![Page 28: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/28.jpg)
28
Inaccessible Object
• An inaccessible object is an unnamed object that was created by operator new and which a programmer has left without a pointer to it.
int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5;
How else can an object become inaccessible?
8
ptr
-5
ptr2
![Page 29: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/29.jpg)
29
Making an Object Inaccessible
int* ptr = new int;
*ptr = 8;
int* ptr2 = new int;
*ptr2 = -5;
ptr = ptr2; // here the 8 becomes inaccessible
8
ptr
-5
ptr2
8
ptr
-5
ptr2
![Page 30: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/30.jpg)
30
Memory Leak
• A memory leak is the loss of available memory space that occurs when dynamic data is allocated but never deallocated.
![Page 31: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/31.jpg)
31
• is a pointer that points to dynamic memory that has been deallocated
int* ptr = new int;
*ptr = 8;
int* ptr2 = new int;
*ptr2 = -5;
ptr = ptr2;
A Dangling Pointer
8
ptr
-5
ptr2
FOR EXAMPLE,
![Page 32: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/32.jpg)
32
int* ptr = new int;
*ptr = 8;
int* ptr2 = new int;
*ptr2 = -5;
ptr = ptr2;
delete ptr2; // ptr is left dangling
ptr2 = NULL;
Leaving a Dangling Pointer
8
ptr
-5
ptr2
8
ptr
NULL
ptr2
![Page 33: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/33.jpg)
33
// SPECIFICATION FILE (dynarray.h)
// Safe integer array class allows run-time specification
// of size, prevents indexes from going out of bounds,
// allows aggregate array copying and initialization.
class DynArray {
public:
DynArray( /* in */ int arrSize );
// Constructor.
// PRE: arrSize is assigned
// POST: IF arrSize >= 1 && enough memory THEN
// Array of size arrSize is created with // all elements == 0 ELSE error message.
DynArray( const DynArray& otherArr );
// Copy constructor.
// POST: this DynArray is a deep copy of otherArr
// Is implicitly called for initialization.
![Page 34: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/34.jpg)
34
// SPECIFICATION FILE continued (dynarray.h)
~DynArray( );
// Destructor.
// POST: Memory for dynamic array deallocated.
int ValueAt ( /* in */ int i ) const;
// PRE: i is assigned.
// POST: IF 0 <= i < size of this array THEN
// FCTVAL == value of array element at index i
// ELSE error message.
void Store ( /* in */ int val, /* in */ int i )
// PRE: val and i are assigned
// POST: IF 0 <= i < size of this array THEN
// val is stored in array element i
// ELSE error message.
![Page 35: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/35.jpg)
35
// SPECIFICATION FILE continued (dynarray.h)
void CopyFrom ( /* in */ DynArray otherArr);// POST: IF enough memory THEN
// new array created (as deep copy) // with size and contents // same as otherArr
// ELSE error message.
private:int* arr ;int size ;
};
![Page 36: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/36.jpg)
36
class DynArray
80
40
90 ? ?
Private data:
size 5
arr 6000
Free store
6000DynArray
Store
ValueAt
DynArray
~DynArray
CopyFrom
![Page 37: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/37.jpg)
37
DynArray beta(5); //constructor
?
?
? ? ?
Private data:
size 5
arr 2000
Free store
2000DynArray
Store
ValueAt
DynArray
~DynArray
CopyFrom
beta
![Page 38: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/38.jpg)
38
DynArray::DynArray( /* in */ int arrSize )
// Constructor.// PRE: arrSize is assigned// POST: IF arrSize >= 1 && enough memory THEN // Array of size arrSize is created with // all elements == 0 ELSE error message.
{int i; if ( arrSize < 1 ) {
cerr << “DynArray constructor - invalid size: “ << arrSize << endl;exit(1);
}
arr = new int[arrSize] ; // allocate memory
size = arrSize;
for (i = 0; i < size; i++)arr[i] = 0;
}
38
![Page 39: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/39.jpg)
39
beta.Store(75, 2);
?
?
75 ? ?
Private data:
size 5
arr 2000
Free store
2000DynArray
Store
ValueAt
DynArray
~DynArray
CopyFrom
beta
![Page 40: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/40.jpg)
40
void DynArray::Store ( /* in */ int val, /* in */ int i ) // PRE: val and i are assigned// POST: IF 0 <= i < size of this array THEN// arr[i] == val// ELSE error message.
{
if ( i < 0 || i >= size ) {cerr << “Store - invalid index : “ << i << endl;exit(1) ;
}
arr[i] = val ;
}
![Page 41: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/41.jpg)
41
?
?
? ?
Private:
size 4
arr 3000
3000 Private:
size 5
arr 2000
2000
?
?
75 ? ?
gamma beta
DynArray gamma(4); //constructor
DynArray
Store
ValueAt
DynArray
~DynArray
CopyFrom
DynArray
Store
ValueAt
DynArray
~DynArray
CopyFrom
![Page 42: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/42.jpg)
42
?
?
-8 ?
Private:
size 4
arr 3000
3000 Private:
size 5
arr 2000
2000
?
?
75 ? ?
gamma beta
gamma.Store(-8,2);
DynArray
Store
ValueAt
DynArray
~DynArray
CopyFrom
DynArray
Store
ValueAt
DynArray
~DynArray
CopyFrom
![Page 43: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/43.jpg)
43
int DynArray::ValueAt ( /* in */ int i ) const // PRE: i is assigned.// POST: IF 0 <= i < size THEN// FCTVAL == arr[i] // ELSE halt with error message.
{
if ( i < 0 || i >= size ) {cerr << “ValueAt - invalid index : “ << i << endl;exit(1) ;
}
return arr[i];
}
![Page 44: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/44.jpg)
44
Why is a destructor needed?
• When a DynArray class variable goes out of scope, the memory space for data members size and pointer arr is deallocated.
• But the dynamic array that arr points to is not automatically deallocated.
• A class destructor is used to deallocate the dynamic memory pointed to by the data member.
![Page 45: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/45.jpg)
45
DynArray::~DynArray( );
// Destructor.
// POST: Memory for dynamic array deallocated.
{
delete [ ] arr ;
}
class DynArray Destructor
![Page 46: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/46.jpg)
46
What happens . . .
• When a function is called that uses pass by value for a
class object of DynArray type?
?
?
75 ? ?
Private:
size 5
arr 2000
2000DynArray
Store
ValueAt
DynArray
~DynArray
CopyFrom
![Page 47: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/47.jpg)
47
// FUNCTION CODE
void SomeFunc( DynArray someArr )
// Uses pass by value
{
.
.
.
.
}
Passing a Class Object by Value
![Page 48: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/48.jpg)
48
By default, Pass-by-value makes a shallow copy
DynArray beta(5); // CLIENT CODE . . .
SomeFunc( beta ); // function call
beta someArr
?
?
75 ?
?
2000DynArray
. . .
Private:
size 5
arr 2000
DynArray
. . .
Private:
size 5
arr 2000
shallow copy
![Page 49: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/49.jpg)
49
Shallow Copy vs. Deep Copy
• a shallow copy copies only the class data members, and does not make a copy of any pointed-to data
• a deep copy copies not only the class data members, but also makes a separate stored copy of any pointed-to data
![Page 50: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/50.jpg)
50
What’s the difference?
• a shallow copy shares the pointed to dynamic data with the original class object
• a deep copy makes its own copy of the pointed to dynamic data at different locations than the original class object
![Page 51: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/51.jpg)
51
?
?
75 ?
?
4000DynArray
. . .
Private:
size 5
arr 4000
beta
someArr
deep copy
?
?
75 ?
?
2000DynArray
. . .
Private:
size 5
arr 2000
Making a (Separate) Deep Copy
![Page 52: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/52.jpg)
52
Initialization of Class Objects
• C++ defines initialization to mean
– initialization in a variable declaration
– passing an object argument by value
– returning an object as the return value of a function
• by default, C++ uses shallow copies for these initializations
![Page 53: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/53.jpg)
53
As a result . . .
• when a class has a data member pointer to dynamically allocated data, you should write what is called a copy constructor
• the copy constructor is implicitly called in initialization situations and makes a deep copy of the dynamic data in a different memory location
![Page 54: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/54.jpg)
54
More about Copy Constructors
• when there is a copy constructor provided for a class, the copy constructor is used to make copies for pass by value
• you do not call the copy constructor
• like other constructors, it has no return type
• because the copy constructor properly defines pass by value for your class, it must use pass by reference in its definition
![Page 55: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/55.jpg)
55
Copy Constructor
• copy constructor is a special member function of a class that is implicitly called in these 3 situations:
– passing object parameters by value
– initializing an object variable in its declaration
– returning an object as the return value of a function
![Page 56: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/56.jpg)
56
?
?
75 ? ?
Private:
size 5
arr 2000
2000 Private:
size 5
arr 4000
4000
?
?
75 ? ?
beta someArr
SomeFunc(beta); // copy-constructor // beta passed by value
DEEP COPY
DynArray
Store
ValueAt
DynArray
~DynArray
CopyFrom
DynArray
Store
ValueAt
DynArray
~DynArray
CopyFrom
![Page 57: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/57.jpg)
57
// FUNCTION CODE
void SomeFunc( DynArray someArr )
// Uses pass by value
{
someArr.Store(290, 2); .
.
.
}
WHAT HAPPENS IN THE SHALLOW COPY SCENARIO?
Suppose SomeFunc calls Store
![Page 58: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/58.jpg)
58
DynArray beta(5); // CLIENT CODE . . .
SomeFunc( beta);
beta.arr[2] has changed
beta someArr
?
?
290 ?
?
2000DynArray
. . .
Private:
size 5
arr 2000
DynArray
. . .
Private:
size 5
arr 2000
shallow copy
![Page 59: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/59.jpg)
59
beta.arr[2] has changed
NOTICE THAT NOT JUST FOR THE SHALLOW COPY, BUT ALSO FOR ARGUMENT beta,THE DYNAMIC DATA HAS CHANGED!
beta someArr
?
?
290 ?
?
2000DynArray
. . .
Private:
size 5
arr 2000
DynArray
. . .
Private:
size 5
arr 2000
shallow copy
![Page 60: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/60.jpg)
60
CONSTRUCTOR
COPY CONSTRUCTOR
DESTRUCTOR
Classes with Data Member Pointers Need
![Page 61: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/61.jpg)
61
DynArray::DynArray( const DynArray& otherArr )// Copy constructor // Implicitly called for deep copy in initializations.// POST: If room on free store THEN// new array of size otherArr.size is created// on free store && arr == its base address // && size == otherArr.size
// && arr[0..size-1] == otherArr.arr[0..size-1]// ELSE error message.
{int i ;size = otherArr.size ;arr = new int[size] ; // allocate memory for copy
for ( i = 0; i< size ; i++ )arr[i] = otherArr.arr[i] ; // copies array
}
61
![Page 62: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/62.jpg)
62
What about the assignment operator?
• the default method used for assignment of class objects makes a shallow copy
• if your class has a data member pointer to dynamic data, you should write a member function to create a deep copy of the dynamic data
![Page 63: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/63.jpg)
63
gamma.CopyFrom(beta);
?
?
75 ? ?
Private:
size 5
arr 3000
3000 Private:
size 5
arr 2000
2000
?
?
75 ? ?
gamma beta
DEEP COPY
DynArray
Store
ValueAt
DynArray
~DynArray
CopyFrom
DynArray
Store
ValueAt
DynArray
~DynArray
CopyFrom
![Page 64: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/64.jpg)
64
void DynArray::CopyFrom ( /* in */ DynArray otherArr )// Creates a deep copy of otherArr. // POST: Array pointed to by arr@entry
deallocated// && IF room on free store // THEN new array is created on free store // && arr == its base address // && size == otherArr.size// && arr[0..size-1] ==
otherArr[0..size-1]// ELSE halts with error message.
{int i ;
delete [ ] arr ; // delete current arraysize = otherArr.size ;arr = new int [size] ; // allocate new array
for ( i = 0; i< size ; i++ ) // deep copy arrayarr[i] = otherArr.arr[i] ;
}64
![Page 65: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/65.jpg)
65
Linked Structures
Data Structures and Algorithms
Week #3
![Page 66: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/66.jpg)
66
Topics
• Meaning of a Linked List• Meaning of a Dynamic Linked List• Traversal, Insertion and Deletion of Elements
in a Dynamic Linked List• Specification of a Dynamic Linked Sorted List• Insertion and Deletion of Elements in a
Dynamic Linked Sorted List
![Page 67: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/67.jpg)
67
What is a List?
• A list is a varying-length, linear collection of homogeneous elements.
• linear means each list element (except the first) has a unique predecessor, and each element (except the last) has a unique successor
![Page 68: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/68.jpg)
68
To implement the List ADT
The programmer must
1) choose a concrete data representation for the list, and
2) implement the list operations
![Page 69: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/69.jpg)
Array-Based Sorted List Operations
Transformers – Insert
– Delete
Observers – IsEmpty
– IsFull
– Length
– IsPresent
change state
observe state
69
![Page 70: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/70.jpg)
70
Array-based class SortedList
IsFull
Length
IsPresent
Delete
IsEmpty
Insert
Private data:
length
data [ 0 ] [ 1 ] [ 2 ]
[MAX_LENGTH-1]
SortedList
![Page 71: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/71.jpg)
71
// SPECIFICATION FILE ARRAY-BASED SORTED LIST ( slist.h )const int MAX_LENGTH = 50 ;typedef int ItemType ;
class SortedList{public : // public member functions
SortedList ( ) ; // constructorbool IsEmpty ( ) const ;bool IsFull ( ) const ; int Length ( ) const ; // returns length of list void Insert ( ItemType item ) ; void Delete ( ItemType item ) ; bool IsPresent( ItemType item ) const ;void Print ( ) ;
private : // private data members
int length ; // number of values currently storedItemType data[MAX_LENGTH] ; void BinSearch ( ItemType item, bool& found, int& position ) const ;
} ;
71
![Page 72: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/72.jpg)
72
How to Implement a List
• use a built-in array stored in contiguous memory locations, implementing operations Insert and Delete by moving list items around in the array, as needed
• use a linked list (to avoid excessive data movement from insertions and deletions) not necessarily stored in contiguous memory locations
![Page 73: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/73.jpg)
73
Implementation Possibilities for a List ADT
List
Linked listBuilt-in array
Built-in dynamic data and pointers
Built-in arrayof structs
![Page 74: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/74.jpg)
74
Self-referential data types
class Node {
private Object data; // the “data”
private Node next; // the “link”
}
data next
![Page 75: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/75.jpg)
75
A Linked List
• a linked list is a list in which the order of the components is determined by an explicit link member in each node
• the nodes are structs--each node contains a component member and also a link member that gives the location of the next node in the list
head ‘X’ ‘C’ ‘L’
![Page 76: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/76.jpg)
76
Dynamic Linked List
head “Ted” “Irv” “Lee”
in a dynamic linked list, nodes are linked together by pointers, and an external pointer (or head pointer) points to the first node in the list
![Page 77: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/77.jpg)
77
Nodes can be located anywhere in memory
the link member holds the memory address of the next node in the list
head 3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
![Page 78: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/78.jpg)
78
// Type DECLARATIONS
struct NodeType {char info;NodeType* link;
}
typedef NodeType* NodePtr;
// Variable DECLARATIONS
NodePtr head;NodePtr ptr;
Declarations for a Dynamic Linked List
. info . link
‘A’ 6000
![Page 79: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/79.jpg)
79
Pointer Dereferencing and Member Selection
. info . link
‘A’ 6000 ptr
ptr
ptr
. info . link
‘A’ 6000
*ptr
ptr
. info . link
(*ptr).info
ptr->info
‘A’ 6000
![Page 80: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/80.jpg)
80
ptr is a pointer to a node
. info . link
‘A’ 6000 ptr
ptr
![Page 81: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/81.jpg)
81
*ptr is the entire node pointed to by ptr
ptr
. info . link
‘A’ 6000
*ptr
![Page 82: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/82.jpg)
82
ptr->info is a node member
ptr
. info . link
ptr->info
(*ptr).info // equivalent
‘A’ 6000
![Page 83: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/83.jpg)
83
ptr->link is a node member
ptr
. info . link
ptr->link
(*ptr).link // equivalent
‘A’ 6000
![Page 84: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/84.jpg)
84
Traversing a Dynamic Linked List
//PRE: head points to a dynamic linked list
ptr = head ;while (ptr != NULL) {
cout << ptr->info ;// Or, do something else with node *ptr
ptr = ptr->link ;}
ptr
3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
head
![Page 85: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/85.jpg)
85
//PRE: head points to a dynamic linked list
ptr = head ;while (ptr != NULL) {
cout << ptr->info ;// Or, do something else with node *ptr
ptr = ptr->link ;}
ptr 3000
3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
head
Traversing a Dynamic Linked List
![Page 86: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/86.jpg)
86
//PRE: head points to a dynamic linked list
ptr = head ;while (ptr != NULL) {
cout << ptr->info ;// Or, do something else with node *ptr
ptr = ptr->link ;}
ptr 3000
3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
head
Traversing a Dynamic Linked List
![Page 87: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/87.jpg)
87
//PRE: head points to a dynamic linked list
ptr = head ;while (ptr != NULL) {
cout << ptr->info ;// Or, do something else with node *ptr
ptr = ptr->link ;}
ptr 3000
3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
head
Traversing a Dynamic Linked List
![Page 88: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/88.jpg)
88
//PRE: head points to a dynamic linked list
ptr = head ;while (ptr != NULL) {
cout << ptr->info ;// Or, do something else with node *ptr
ptr = ptr->link ;}
ptr 5000
3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
head
Traversing a Dynamic Linked List
![Page 89: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/89.jpg)
89
//PRE: head points to a dynamic linked list
ptr = head ;while (ptr != NULL) {
cout << ptr->info ;// Or, do something else with node *ptr
ptr = ptr->link ;}
ptr 5000
3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
head
Traversing a Dynamic Linked List
![Page 90: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/90.jpg)
90
//PRE: head points to a dynamic linked list
ptr = head ;while (ptr != NULL) {
cout << ptr->info ;// Or, do something else with node *ptr
ptr = ptr->link ;}
ptr 5000
3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
head
Traversing a Dynamic Linked List
![Page 91: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/91.jpg)
91
//PRE: head points to a dynamic linked list
ptr = head ;while (ptr != NULL) {
cout << ptr->info ;// Or, do something else with node *ptr
ptr = ptr->link ;}
ptr 2000
3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
head
Traversing a Dynamic Linked List
![Page 92: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/92.jpg)
92
//PRE: head points to a dynamic linked list
ptr = head ;while (ptr != NULL) {
cout << ptr->info ;// Or, do something else with node *ptr
ptr = ptr->link ;}
ptr 2000
3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
head
Traversing a Dynamic Linked List
![Page 93: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/93.jpg)
93
//PRE: head points to a dynamic linked list
ptr = head ;while (ptr != NULL) {
cout << ptr->info ;// Or, do something else with node *ptr
ptr = ptr->link ;}
ptr 2000
3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
head
Traversing a Dynamic Linked List
![Page 94: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/94.jpg)
94
//PRE: head points to a dynamic linked list
ptr = head ;while (ptr != NULL) {
cout << ptr->info ;// Or, do something else with node *ptr
ptr = ptr->link ;}
ptr NULL
3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
head
Traversing a Dynamic Linked List
![Page 95: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/95.jpg)
95
//PRE: head points to a dynamic linked list
ptr = head ;while (ptr != NULL) {
cout << ptr->info ;// Or, do something else with node *ptr
ptr = ptr->link ;}
ptr NULL
3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
head
Traversing a Dynamic Linked List
![Page 96: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/96.jpg)
Using Operator new
If memory is available in an area called the free store (or heap), operator new allocates the requested object, and returns a pointer to the memory allocated.
The dynamically allocated object exists until the delete operator destroys it.
96
![Page 97: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/97.jpg)
97
Inserting a Node at the Front of a List
char item = ‘B’;NodePtr location;location = new NodeType;location->info = item;location->link = head;head = location;
head ‘X’ ‘C’ ‘L’
‘B’item
![Page 98: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/98.jpg)
98
Inserting a Node at the Front of a List
char item = ‘B’;NodePtr location;location = new NodeType;location->info = item;location->link = head;head = location;
head ‘X’ ‘C’ ‘L’
‘B’item
location
![Page 99: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/99.jpg)
99
Inserting a Node at the Front of a List
char item = ‘B’;NodePtr location;location = new NodeType;location->info = item;location->link = head;head = location;
head ‘X’ ‘C’ ‘L’
‘B’item
location
![Page 100: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/100.jpg)
100
Inserting a Node at the Front of a List
char item = ‘B’;NodePtr location;location = new NodeType;location->info = item;location->link = head;head = location;
head ‘X’ ‘C’ ‘L’
‘B’item
location ‘B’
![Page 101: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/101.jpg)
101
Inserting a Node at the Front of a List
char item = ‘B’;NodePtr location;location = new NodeType;location->info = item;location->link = head;head = location;
head ‘X’ ‘C’ ‘L’
‘B’item
location ‘B’
![Page 102: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/102.jpg)
102
Inserting a Node at the Front of a List
char item = ‘B’;NodePtr location;location = new NodeType;location->info = item;location->link = head;head = location;
head ‘X’ ‘C’ ‘L’
‘B’item
location ‘B’
![Page 103: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/103.jpg)
• The object currently pointed to by the pointer is deallocated, and the pointer is considered undefined. The object’s memory is returned to the free store.
Using Operator delete
103
![Page 104: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/104.jpg)
104
Deleting the First Node from the List
NodePtr tempPtr;
item = head->info;tempPtr = head;head = head->link;delete tempPtr;
head
item
‘B’ ‘X’ ‘C’ ‘L’
tempPtr
![Page 105: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/105.jpg)
105
Deleting the First Node from the List
NodeType * tempPtr;
item = head->info;tempPtr = head;head = head->link;delete tempPtr;
head
item
‘B’ ‘X’ ‘C’ ‘L’
tempPtr
‘B’
![Page 106: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/106.jpg)
106
Deleting the First Node from the List
NodeType * tempPtr;
item = head->info;tempPtr = head;head = head->link;delete tempPtr;
head
item
‘B’ ‘X’ ‘C’ ‘L’
tempPtr
‘B’
![Page 107: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/107.jpg)
107
Deleting the First Node from the List
NodeType * tempPtr;
item = head->info;tempPtr = head;head = head->link;delete tempPtr;
head
item
‘B’ ‘X’ ‘C’ ‘L’
tempPtr
‘B’
![Page 108: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/108.jpg)
108
Deleting the First Node from the List
NodeType * tempPtr;
item = head->info;tempPtr = head;head = head->link;delete tempPtr;
head
item
‘X’ ‘C’ ‘L’
tempPtr
‘B’
![Page 109: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/109.jpg)
109
What is a List?
• a list is a varying-length, linear collection of homogeneous elements
• linear means each list element (except the first) has a unique predecessor, and each element (except the last) has a unique successor
![Page 110: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/110.jpg)
ADT Unsorted List OperationsTransformers
– Create – InsertAfter – InsertBefore– Delete
Observers – IsFull– IsEmpty– EndOfList– CurrentItem
Iterators – Reset – Advance
change state
observe state
process all
110
![Page 111: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/111.jpg)
111
class PersonList
Private data:
head
currPtr
~PersonList
IsEmpty
Advance . . .
InsertAfter
PersonList
CurrentRec
Delete
13 21
E d \0M a x \0
![Page 112: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/112.jpg)
// SPECIFICATION FILE person.h
#include “bool.h” . . .
struct PersonRec{
char* name ; // Pointer to person’s nameint age ; // Person’s age
} ;
typedef PersonNode* NodePtr;
struct PersonNode{
char* name ;// Pointer to person’s nameint age ; // Person’s ageNodePtr link ; // Pointer to next node in list
} ;
112
![Page 113: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/113.jpg)
// SPECIFICATION FILE continued person.h
class PersonList{public : // LINKED LIST IMPLEMENTATION
PersonList ( ) ;~PersonList ( ) ;Boolean IsEmpty ( ) const ;Boolean IsFull ( ) const ; void Reset ( ) ; Boolean EndOfList ( ) const ;void InsertAfter ( PersonRec someRec ) ; void InsertBefore ( PersonRec someRec ) ; void Advance ( );
void Delete ( ) ;PersonRec CurrentRec ( ) const ;
private :PersonNode* head ;PersonNode* currPtr ;
} ;113
![Page 114: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/114.jpg)
// LINKED LIST IMPLEMENTATION FILE ( person.cpp )
#include “person.h”
. . .
PersonList::PersonList ( ) // constructor
// PRE: None.
// POST: Empty list created && EndOfList( ).
{
head = NULL;
currPtr = NULL;
}
Boolean PersonList::IsEmpty ( ) const // POST: FCTVAL == ( list is empty )
{
return ( head == NULL ) ;
}
114
![Page 115: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/115.jpg)
// IMPLEMENTATION CONTINUED ( person.cpp )
void PersonList::Reset ( ) // PRE: NOT IsEmpty ( )
// POST: List cursor is at front of list
{
currPtr = head ;
}
PersonRec PersonList::CurrentRec ( ) const // PRE: NOT IsEmpty ( ) && NOT EndOfList ( )
// POST: FCTVAL == record at list cursor
{
PersonRec rec ;
rec.name = currPtr->name ;
rec.age = currPtr->age ;
return rec ;
} 115
![Page 116: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/116.jpg)
Boolean PersonList::EndOfList ( ) const // POST: FCTVAL == ( list cursor is beyond end of list ){
return ( currPtr == NULL ) ;}
void PersonList::Advance ( )// PRE: NOT IsEmpty( ) && NOT EndOfList( )// POST: List cursor has advanced to next record{
currPtr = currPtr->link ;}
PersonList::~PersonList ( ) // destructor// POST: List destroyed{
currPtr = head ;while ( ! EndOfList ( ) )
Delete ( ) ;}
116
![Page 117: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/117.jpg)
void PersonList::InsertAfter ( /* in */ PersonRec someRec )
// PRE: Assigned (someRec) && NOT IsEmpty( )// && NOT IsFull ( ) && NOT EndOfList ( )
// POST: someRec inserted after list cursor// && This new node has become the current record{
// obtain and fill a nodeNodePtr ptr = new PersonNode ;
ptr->name = new char [ strlen ( someRec.name) + 1 ] ;strcpy( ptr->name, someRec.name );ptr->age = someRec.age ;ptr->link = currPtr->link ;currPtr->link = ptr ;currPtr = ptr ;
}
117
![Page 118: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/118.jpg)
118
Private data:
head
currPtr
~PersonList
IsEmpty
Advance . . .
InsertAfter
PersonList
CurrentRec
Delete
Insert into the PersonList
13 21
M a x \0 E d \0
16
Ted \0
![Page 119: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/119.jpg)
Inserting into the PersonList
after list cursorsomeRec
16
Ted \0
Private data:
head
currPtr
13 21
E d \0M a x \0
50
![Page 120: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/120.jpg)
120
NodePtr ptr = new PersonNode ;
someRec
ptr
16
Ted \0
Private data:
head
currPtr
13 21
E d \0M a x \0
![Page 121: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/121.jpg)
121
ptr->name = new char[4] ;
Private data:
head
currPtr
13 21
E d \0M a x \0
16
Ted \0
someRec
ptr
![Page 122: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/122.jpg)
122
strcpy( ptr->name, someRec.name ) ;
Private data:
head
currPtr
13 21
E d \0M a x \0
16
Ted \0
someRec
ptr
Ted \0
![Page 123: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/123.jpg)
123
ptr->age = someRec.age ;
Private data:
head
currPtr
13 21
E d \0M a x \0
16
Ted \0
someRec
ptr
Ted \0
16
![Page 124: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/124.jpg)
124
ptr->link = currPtr->link ;
Private data:
head
currPtr
13 21
E d \0M a x \0
16
Ted \0
someRec
ptr
Ted \0
16
![Page 125: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/125.jpg)
125
currPtr->link = ptr ;
Private data:
head
currPtr
13 21
E d \0M a x \0
16
Ted \0
someRec
ptr
Ted \0
![Page 126: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/126.jpg)
126
currPtr = ptr ;
“Ted” 16
Private data:
head
currPtr
13 21
E d \0M a x \0
16
Ted \0
someRec
ptr
![Page 127: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/127.jpg)
127
Insert algorithm
• How would the algorithm to Insert an item differ for a sorted linked list?
• That is, for a linked list with the following class invariant:
// CLASSINV: list elements sorted in ascending order
![Page 128: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/128.jpg)
128
class SortedList2
~SortedList2
Insert
InsertTop
SortedList2
IsEmpty
Delete
‘C’ ‘L’ ‘X’
Private data:
head
DeleteTop
![Page 129: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/129.jpg)
ADT SortedList2 Operations
Transformers – InsertTop
– Insert
– DeleteTop
– Delete
Observers
– IsEmpty
change state
observe state
129
![Page 130: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/130.jpg)
130
// SPECIFICATION FILE DYNAMIC-LINKED SORTED LIST( slist2.h )
typedef int ItemType ; // Type of each component // is simple type or string type
struct NodeType{
ItemType item ; // Pointer to person’s nameNodeType* link ; // link to next node in list
} ;
typedef NodeType* NodePtr;
struct NodeType
![Page 131: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/131.jpg)
131
// SPECIFICATION FILE DYNAMIC-LINKED SORTED LIST( slist2.h )
class SortedList2{public :
bool IsEmpty ( ) const ;
void Print ( ) const ;
void InsertTop ( /* in */ ItemType item ) ;
void Insert ( /* in */ ItemType item ) ;
void DeleteTop ( /* out */ ItemType& item ) ;
void Delete ( /* in */ ItemType item );
SortedList2 ( ) ; // Constructor~SortedList2 ( ) ; // DestructorSortedList2 ( const SortedList2& otherList ) ; // Copy-constructor
private :
NodeType* head;} ;
131
![Page 132: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/132.jpg)
132
Insert Algorithm
• what will be the algorithm to Insert an item into its proper place in a sorted linked list?
• that is, for a linked list whose elements are maintained in ascending order?
![Page 133: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/133.jpg)
133
Insert algorithm for SortedList2
• find proper position for the new element in the sorted list using two pointers prevPtr and currPtr, where prevPtr trails behind currPtr
• obtain a node for insertion and place item in it
• insert the node by adjusting pointers
![Page 134: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/134.jpg)
134
Implementing SortedList2Member Function Insert
// DYNAMIC LINKED LIST IMPLEMENTATION (slist2.cpp)
void SortedList2 :: Insert ( /* in */ ItemType item )
// PRE: item is assigned && List components in ascending order
// POST: item is in List && List components in ascending order{
.
.
.
}
![Page 135: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/135.jpg)
135
Inserting ‘S’ into a Sorted List
‘C’ ‘L’ ‘X’
Private data:
head
prevPtr currPtr
![Page 136: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/136.jpg)
136
Finding Proper Position for ‘S’
‘C’ ‘L’ ‘X’
Private data:
head
prevPtr currPtr
NULL
![Page 137: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/137.jpg)
137
‘C’ ‘L’ ‘X’
Private data:
head
prevPtr currPtr
Finding Proper Position for ‘S’
![Page 138: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/138.jpg)
138
‘C’ ‘L’ ‘X’
Private data:
head
prevPtr currPtr
Finding Proper Position for ‘S’
![Page 139: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/139.jpg)
139
‘C’ ‘L’ ‘X’
Private data:
head
prevPtr currPtr
Inserting ‘S’ into Proper Position
‘S’
![Page 140: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/140.jpg)
140
// IMPLEMENTATION DYNAMIC-LINKED SORTED LIST (slist2.cpp)
SortedList2 ::SortedList2 ( ) // Constructor// Post: head == NULL{
head = NULL ;}
SortedList2 :: ~SortedList2 ( ) // Destructor// Post: All linked nodes deallocated {
ItemType temp ;// keep deleting top node
while ( !IsEmpty )DeleteTop ( temp );
}140
![Page 141: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/141.jpg)
141
void SortedList2 :: Insert( /* in */ ItemType item ) // Pre: item is assigned && list components in ascending order
// Post: new node containing item is in its proper place
// && list components in ascending order
{ NodePtr currPtr ;
NodePtr prevPtr ;
NodePtr location ;
location = new NodeType ;
newNodePtr->info = item ;
prevPtr = NULL ;
currPtr = head ;
while ( currPtr != NULL && item > currPtr->info )
{ prevPtr = currPtr ; // advance both pointers currPtr = currPtr->link ;
}
location->link = currPtr ; // insert new node here
if ( prevPtr == NULL )
head = location ;
else
prevPtr->link = location ;
}141
![Page 142: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/142.jpg)
142
void SortedList2 :: DeleteTop ( /* out */ ItemType& item )
// Pre: list is not empty && list elements in ascending order
// Post: item == element of first list node @ entry
// && node containing item is no longer in linked list
// && list elements in ascending order
{
NodePtr tempPtr = head ;
// obtain item and advance head
item = head->info ;
head = head->link ;
delete tempPtr ;
}
![Page 143: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/143.jpg)
143
void SortedList2 :: Delete ( /* in */ ItemType item ) // Pre: list is not empty && list elements in ascending order// && item == component member of some list node// Post: item == element of first list node @ entry// && node containing first occurrence of item is no longer // in linked list && list elements in ascending order
{ NodePtr delPtr ;NodePtr currPtr ; // Is item in first node? if ( item == head->info ){ delPtr = head ; // If so, delete first node
head = head->link ;}
else { // search for item in rest of listcurrPtr = head ;while ( currPtr->link->info != item )
currPtr = currPtr->link ;delPtr = currPtr->link ;currPtr->link = currPtr->link->link ;
}
delete delPtr ;} 143
![Page 144: 1 Data Structures and Algorithms Pointers and Dynamic Data.](https://reader033.fdocuments.net/reader033/viewer/2022051820/56649efe5503460f94c1360e/html5/thumbnails/144.jpg)
144
class SortedList2
~SortedList2
Insert
InsertTop
SortedList2
IsEmpty
Delete
‘C’ L’
Private data:
head
DeleteTop
‘S’ ‘X’