Upload
raya-anderson
View
57
Download
0
Embed Size (px)
DESCRIPTION
Pointer: Dynamic Allocation This lecture prepared by the instructors at the University of Manitoba in Canada and has been modified by Dr. Ahmad Reza Hadaegh. Dynamic Allocation - Main memory can be thought of as a (very) large one-dimensional array of memory locations - PowerPoint PPT Presentation
Citation preview
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
1
Pointer: Dynamic Allocation
This lecture prepared by the instructors at the University of Manitoba in Canada and has been modified by Dr. Ahmad Reza Hadaegh
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
2
Dynamic Allocation
- Main memory can be thought of as a (very) large one-dimensional array of memory locations
- Each location holds 1 byte and has its own address
- Starts at 0 in increments of 1- Usually in hexadecimal- 0000 - FFFF represents 64K of memory
- 64 * 1024 = 65,536 memory locations
0000
0001
0002
0003
0004
0005
FFFF
••
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
3
Dynamic Allocation
- When variables are declared they are allocated memory
- An integer requires (say) 4 bytes and thus gets 4 consecutive locations in memory
- Most machines would store an int in 4 bytes
- The address of the integer is the first byte and is effectively stored via the variable name
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
4
Dynamic Allocation
- An integer variable X would effectively “point” to the starting address of the 4 bytes required
- X must be dereferenced in order to be used- Dereference means to interpret what exists at a particular memory location
- Dereference is implicit here
memoryinteger variable X
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
5
Dynamic Allocation
- It is possible to explicitly declare a variable that contains the address of other variables
- Creating variables that are pointers
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
6
Dynamic Allocation
typedefint* intptr;
int main ( ) {intptr ptr1;
intptr is a pointer toan integer
•••
Must be a pointer to a valid C++ type (either built-in or user defined type)
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
7
Dynamic Allocation
Syntax notes:
int main ( ) { int* ptr1; int* ptr2; int* ptr3;
•••
int main ( ) { int *ptr1, *ptr2, *ptr3;
•••
is the same as ...
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
8
Dynamic Allocation
- A pointer in C++ must point to storage of a particular type ptr1 is a pointer to an integer
- ptr1 is a 4 byte variable that is able to point to a 4 byte variable
- The value of ptr1 is not initialized and is at this point garbage
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
9
Dynamic Allocation
- To allocate storage for ptr1 to point to:
4 bytes of storage allocated for ptr1 to point to
typedef int* intptr;
int main ( ) { intptr ptr1; ptr1 = new int; •
••
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
10
Dynamic Allocation
- Unlike “normal” variables, pointers must be explicitly dereferenced
*ptr1 = 200;
Store 200 in the4 bytes pointed toby ptr1
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
11
Dynamic Allocation
- Other manipulation may take place
i = *ptr1;
Assign 200 to integer variable i
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
12
Dynamic Allocation
Other manipulation may not sensibly take place
i = ptr1;
Assign the addressthat ptr1 points toto integer variable i?
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
13
Dynamic Allocation
- What happens here? ptr1 only exists once --as such, each “new” pointsptr1 to newly allocated 2 byte area
The first 999 storage areasare reserved by the OS, butno longer accessible
Memory leak!
typedef int* intptr;
void main () { intptr ptr1; int i; for (i=1;i<=1000;i++) { ptr1 = new int; *ptr1 = 1234; }}
- Memory leaks are common problems in many applications
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
14
Dynamic Allocation
- Storage that is allocated via “new” should be freed via “delete” during the execution of a program
Not really useful, but you get the point
typedef int* intptr;
void main () { intptr ptr1; int i; for (i=1;i<=1000;i++) { ptr1 = new int; *ptr1 = 1234; delete ptr1; }}
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
15
Dynamic Allocation
typedef int* intptr;
void main () { intptr P, Q; P = new int; *P = 1 Q = new int; *Q = 2; cout << *P << ‘ ’ << *Q << endl; *P = *Q + 3; cout << *P << ‘ ’ << *Q << endl; P = Q; cout << *P << ‘ ’ << *Q << endl; }
P
Q
?
?
•••
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
16
Dynamic Allocation
typedef int* intptr;
void main () { intptr P, Q; P = new int; *P = 1 Q = new int; *Q = 2; cout << *P << ‘ ’ << *Q << endl; *P = *Q + 3; cout << *P << ‘ ’ << *Q << endl; P = Q; cout << *P << ‘ ’ << *Q << endl; }
P
Q
?
?
•••
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
17
Dynamic Allocation
typedef int* intptr;
void main () { intptr P, Q; P = new int; *P = 1 Q = new int; *Q = 2; cout << *P << ‘ ’ << *Q << endl; *P = *Q + 3; cout << *P << ‘ ’ << *Q << endl; P = Q; cout << *P << ‘ ’ << *Q << endl; }
P
Q
1
?
•••
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
18
Dynamic Allocation
typedef int* intptr;
void main () { intptr P, Q; P = new int; *P = 1 Q = new int; *Q = 2; cout << *P << ‘ ’ << *Q << endl; *P = *Q + 3; cout << *P << ‘ ’ << *Q << endl; P = Q; cout << *P << ‘ ’ << *Q << endl; }
P
Q
1
?
•••
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
19
Dynamic Allocation
typedef int* intptr;
void main () { intptr P, Q; P = new int; *P = 1 Q = new int; *Q = 2; cout << *P << ‘ ’ << *Q << endl; *P = *Q + 3; cout << *P << ‘ ’ << *Q << endl; P = Q; cout << *P << ‘ ’ << *Q << endl; }
P
Q
1
2
•••
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
20
Dynamic Allocation
typedef int* intptr;
void main () { intptr P, Q; P = new int; *P = 1 Q = new int; *Q = 2; cout << *P << ‘ ’ << *Q << endl; *P = *Q + 3; cout << *P << ‘ ’ << *Q << endl; P = Q; cout << *P << ‘ ’ << *Q << endl; }
P
Q
1
2
•••
Output: 1 2
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
21
Dynamic Allocation
typedef int* intptr;
void main () { intptr P, Q; P = new int; *P = 1 Q = new int; *Q = 2; cout << *P << ‘ ’ << *Q << endl; *P = *Q + 3; cout << *P << ‘ ’ << *Q << endl; P = Q; cout << *P << ‘ ’ << *Q << endl; }
P
Q
5
2
•••
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
22
Dynamic Allocation
typedef int* intptr;
void main () { intptr P, Q; P = new int; *P = 1 Q = new int; *Q = 2; cout << *P << ‘ ’ << *Q << endl; *P = *Q + 3; cout << *P << ‘ ’ << *Q << endl; P = Q; cout << *P << ‘ ’ << *Q << endl; }
P
Q
5
2
•••
Output: 5 2
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
23
Dynamic Allocation
typedef int* intptr;
void main () { intptr P, Q; P = new int; *P = 1 Q = new int; *Q = 2; cout << *P << ‘ ’ << *Q << endl; *P = *Q + 3; cout << *P << ‘ ’ << *Q << endl; P = Q; cout << *P << ‘ ’ << *Q << endl; }
P
Q
5
2
•••
Memory leak!
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
24
Dynamic Allocation
typedef int* intptr;
void main () { intptr P, Q; P = new int; *P = 1 Q = new int; *Q = 2; cout << *P << ‘ ’ << *Q << endl; *P = *Q + 3; cout << *P << ‘ ’ << *Q << endl; P = Q; cout << *P << ‘ ’ << *Q << endl; }
P
Q
5
2
•••
Memory leak!
Output: 2 2
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
25
Dynamic Allocation
*P = 7; cout << *P << ‘ ’ << *Q << endl; P = new int; delete P; P = NULL; Q = NULL; }
P
Q
5
7
•••
Memory leak!
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
26
Dynamic Allocation
*P = 7; cout << *P << ‘ ’ << *Q <<endl P = new int; delete P; P = NULL; Q = NULL; }
P
Q
5
7
•••
Memory leak!
Output: 7 7
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
27
Dynamic Allocation
*P = 7; cout << *P << ‘ ’ << *Q << endl; P = new int; delete P; P = NULL; Q = NULL; }
P
Q
5
7
•••
Memory leak!
?
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
28
Dynamic Allocation
*P = 7; cout << *P << ‘ ’ << *Q << endl; P = new int; delete P; P = NULL; Q = NULL; }
P
Q
5
7
•••
Memory leak!
?
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
29
Dynamic Allocation
*P = 7; cout << *P << ‘ ’ << *Q << endl; P = new int; delete P; P = NULL; Q = NULL; }
P
Q
5
7
••• Memory leak!
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
30
Dynamic Allocation
*P = 7; cout << *P << ‘ ’ << *Q << endl; P = new int; delete P; P = NULL; Q = NULL; }
P
Q
5
7
•••
Memory leaks!
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
31
Dynamic Allocation
NULL- Is a built-in constant that sets a pointer variable to something that can not be dereferenced- Also makes it clear that a pointer variable is in fact not pointing to anything
- A garbage pointer may be non NULL and thus look like it’s pointing to something
if (some_pointer = = NULL) cout << “pointer points to nothing” << endl;
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
32
Dynamic Allocation
- Pointer variables can be initialized to NULL
intptr a=NULL, b=NULL, c=NULL;
- Probably a good habit to set pointer variables to NULL after deleting them
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
33
Dynamic Allocation
#include <iostream>using namespace std;
typedef int* intptr;
void main () { intptr ptr1; ptr1 = new int; *ptr1 = 12345; delete ptr1; cout << *ptr1 << endl; }
Output?
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
34
Dynamic Allocation
#include <iostream>using namespace std;
typedef int* intptr;
void main () { intptr ptr1; ptr1 = new int; *ptr1 = 12345; delete ptr1; ptr1 = NULL; cout << *ptr1 << endl;}
Output?
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
35
Dynamic Allocation
- Using NULL does not guarantee that that you protect yourself from doing something silly as in:
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
36
Dynamic Allocation
#include <iostream>using namespace std;
typedef int* intptr;
void main () { intptr ptr1; ptr1 = new int; *ptr1 = 12345; delete ptr1; ptr1 = NULL; ptr1 = new int; cout << *ptr1 << endl; }
Output?
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
37
Dynamic Allocation#include <iostream>using namespace std;
typedef int* intptr;
void main () { intptr ptr1, ptr2; ptr1 = new int; *ptr1 = 12345; delete ptr1; ptr1 = NULL; ptr2 = new int; ptr1 = new int; cout << *ptr1 << endl; }
Output?
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
38
Dynamic Allocation
- When dealing with pointers, you are responsible for ensuring they do not dangle
Note:- Dynamic allocation is one of the most important topic of this course. So you need understand it very well.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
40
Link List: Linked structures
- Linked lists often provide an elegant alternative to structures such as arrays
- A linked list is readily created in most procedural languages Linked lists are often represented in the following manner:
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
41
Linked Lists
node
Pointer tonext node
Last node’s pointeris NULL
top
27 -38 4 36
Data
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
42
Linked List
- The simplest linked structure- Sometimes called a linear linked list
- The result of having an initial pointer to a node - And dynamically created nodes that point to other nodes
- A dynamic incarnation of a simple array- Both have their advantages
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
43
Linked Lists
- Big advantage over array in that linked list is dynamically created
- Use only as many nodes as required for data- List grows and shrinks accordingly
- Linked lists are made up of a pointer (“top” in this case) that points to the first of a collection of homogeneous nodes
- Unlike the nodes, top contains no data top is not dynamically
created while the rest of the linked structure is
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
44
Declaration for linked list
class node;typedef node* nodeptr;
class node { public: int number; nodeptr next; };
//--------------------------------int main ( ) { nodeptr top; ….}
Only variable declared
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
45
Linked Lists
- All that exists at this time is an uninitialized pointer to a node- No nodes have been allocated yet
- To make it clear the linked list is empty
top = NULL;
•••
•••
NULL is a specialC++ constant
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
46
Dereferencing: Allocating a node
- The Code:
top = new node;
- Allocates space for a new node and place its starting memory address in top
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
47
Dereferencing
- Given that a node exists and given that a pointer exists that contains the node’s address, the contents of the node may be modified
- Again, using a pointer to reference storage is called dereferencing
top -> number = 123;top -> next = NULL;
Note the arrow notation that allows access to a field within a node
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
48
Dereferencing
- Now have:
top
Remember that top is a declared variable -- a pointer to a node
This node is not a variable --it is dynamically allocatedvia the new statement
123
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
49
New (again)
top = new node; // again!
top
123
top
123
top now pointsto a new node
Old node still exists, butcan no longer be accessed --memory leak!
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
50
Delete
- Linked lists are dynamic which means they can grow and shrink appropriately
- Grow with new
- Shrink with delete
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
51
Delete
- delete top;
top
123
top
123
top now containsgarbage
Node might still exist, butis at the control of the OS
?
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
52
Insert
- Inserting many nodes:
- Important to be able to insert more than a single node into a linked list
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
53
Insert
- Assume an existing linked list structure and definition
nodeptr newnode;
top
27 -38 4 36
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
54
Insertnewnode = new node;newnode -> number = 123;newnode -> next = top;top = newnode;
top
27 -38 4 36
123
newnode
This code assumes you always want to place a newly allocated node at the front of the list
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
55
Searching
- Many operations upon a linked structures involve searching.
bool search (nodeptr top, int key) { nodeptr curr=top; bool found=false; while ((curr != NULL) && (!found)) if (curr -> number == key) found = true; else curr = curr -> next; return (found);}
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
56
More on Inserting
- Have seen inserting a node to the front of a linked list
- Possible that this might not be satisfactory
- If a list is to be maintained in sorted order (for example), an insert might have to be done in the middle or the the end of the list
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
57
Find insertionpoint (prev)
Insert
More on Insert
void insert (nodeptr& top, int item) { nodeptr curr=top, prev=NULL, newnode; bool found=false; newnode = new node; newnode -> number = item; while ((curr != NULL) and (!found)) if (item > curr -> number) { prev = curr; curr = curr -> next; } else found = true;
newnode -> next = curr; if (prev == NULL) top = newnode; else prev -> next = newnode; }
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
58
Deleting
- Removing items from a linked list will normally require a search and knowledge of different cases of delete (much like insert)
- Deleting the first node of a linked list requires the manipulation of the “top” pointer
- Deleting a node in the middle of a linked list requires the manipulation of pointers within allocated nodes -- “top” pointer will remain unchanged
- Deleting at the end of a linked list requires the same operations as delete in the middle
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
59
Deleting
void remove (nodeptr& top, int key) { nodeptr curr, temp; // Code assumes key will be found if (key == top -> number) { temp = top; top = top -> next; } else { curr = top; while (curr -> next -> number != key) curr = curr -> next; temp = curr -> next; curr -> next = curr -> next -> next; } delete temp;}
Double dereference
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
60
Deleting
- For every node that is allocated via new, there should be a node given back to the OS via delete
- This implies that a function should probably exist to destroy an existing linked list
void destroy (nodeptr& top) { nodeptr curr=top, temp; while (curr != NULL) { temp = curr; curr = curr -> next; delete temp; } top = NULL;}
If you declare and create alinked list within a functionwithout destroying it, you will have a memory leak when you leave the function ends
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
61
Copying
- Functions can work with more than one linked list at a time- Here is a function that copies one linked list to another:void copy (nodeptr atop, nodeptr& btop) { nodeptr acurr, bcurr; destroy (btop); // deleted previous nodes in the list if there is any if (atop != NULL) { btop = new node; btop -> number = atop -> number; acurr = atop; bcurr = btop; while (acurr -> next != NULL) { bcurr -> next = new node; acurr = acurr -> next; bcurr = bcurr -> next; bcurr -> number = acurr -> number; } bcurr -> next = NULL; } }
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
62
Linked lists
- Linked lists are general purpose structures that can be manipulated to solve a diverse set of problems
- Working successfully with linked lists takes study and practice
- It really helps if you understand the basics
< See: Example 1>
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
63
Object-Oriented Programming
with
Link List
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
64
Linked Lists and Classes
class node;
typedef Node* NodePtr;
class node { public: int number; NodePtr next;};
As before
… but in addition, now have another class:
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
65
Linked Lists and Classes
class LL { private: NodePtr top; void destroy(NodePtr&); public: LL(); ~LL(); void buildLL(int); void printLL();};
- A linked list is now defined as a class itself
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
66
Linked Lists and Classes
void main () { LL list1, list2, list3; …}
list1, list2, and list3 are three instances of the LLclass. list1, list2, and list3are also called objects.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
67
Linked Lists and Classes
- A class is made up of data and methods
class LL { private: NodePtr top; void destroy(NodePtr&); public: LL(); ~LL(); void buildLL(int); void printLL(); };
datum
method
This class definitionhas 5 method prototypesand one datum.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
68
Linked Lists and Classes
- Data and methods of a class definition can be public or private
- Public:- Accessible by the world (scoping rules still apply)
- Private:- Accessible only by member functions
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
69
Linked Lists and Classes
- Placing data and methods within the private portion of a class definition protects them from “outside” harm
- Sometimes called data hiding
- The only way hidden data and methods can be accessed is indirectly via public methods
- Methods and data are bound together
- Encapsulation
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
70
Linked Lists and Classes
class LL { private: NodePtr top; void destroy(NodePtr&); public: LL(); ~LL(); void buildLL(int); void printLL(); };
Can only beaccessed by
A linked list (LL) is nowan encapsulated package of data and a limited numberof methods that work uponthat data.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
71
Linked Lists and Classes
- In the procedural linked list example- Top pointers were set to NULL before use- Nodes within linked list were deleted before linked list left scope
- Remember that the top pointer has been defined as automatic and will cease to exist when the linked list leaves scope
- The allocated memory will live on until deleted
- Programmer’s responsibility to ensure initialization and destruction takes place properly
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
72
Linked Lists and Classes
- Objects can have constructors - Method that is automatically invoked when an object is created
- Allows for initialization to take place
- Objects can have destructors- Method that is automatically invoked when an object leaves scope
- Allows for clean up to take place
- Constructors and destructors are not normally called explicitly
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
73
Linked Lists and Classes
class LL { private: NodePtr top; void destroy(NodePtr&);
public: LL(); ~LL(); void buildLL(int); void printLL(); };
constructordestructor
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
74
LL::LL() { // Linked list constructor
top = NULL;}
Linked Lists and Classes
Scope resolution operator -- lets thecompiler know that what you’re definingis a member function of the class LL
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
75
LL::~LL() { // Linked list destructor -- will call a private // member function “destroy” that will perform // a deep deletion of the linked list object
destroy (top) ; }
Linked Lists and Classes
This destructor will automatically be invoked when an instance of LLleaves scope
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
76
Linked Lists and Classes
void LL::destroy(NodePtr& head){ // Deep delete a linked list pointed at by “head”
NodePtr curr, temp;
curr = head; while (curr != NULL) { temp = curr; curr = curr->next; delete temp; } head = NULL;}
Very much like a regularprocedural function -- doesnot operate directly on data components of the object
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
77
Linked Lists and Classes
void LL::buildLL(int size) {// "build” will create an ordered linked list consisting// of the first "size" even integers
NodePtr newNode; int i;
destroy(top); //Destroy self before building linked list.
for (i=size;i>0;i--) { newNode = new (Node); newNode->next = top; newNode->number = i*2; top = newNode; } }
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
78
Linked Lists and Classes
void LL::printLL() {// "print" will output the entire linked list to // the standard output device --// one "number" per line.
NodePtr curr;
curr = top; while (curr != NULL) { cout << curr->number << endl; curr = curr->next; }}
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
79
Linked Lists and Classes
Member functions are invoked as follows:
void main () { LL list1, list2, list3; list1.buildLL(10); list2.buildLL(20); list3.buildLL(50);
list1.buildLL(40);
list1.printLL(); list2.printLL(); list3.printLL();}
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
80
Linked Lists and Classes
void main () { LL list1, list2, list3; list1.buildLL(10); list2.buildLL(20); list3.buildLL(50);
list1.buildLL(40);
list1.printLL(); list2.printLL(); list3.printLL(); }
Member functions are called as if theywere a part of a structure -- which they are
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
81
Linked Lists and Classes
void main () { LL list1, list2, list3; list1.buildLL(10); list2.buildLL(20); list3.buildLL(50) list1.buildLL(40); list1.printLL(); list2.printLL(); list3.printLL();
}
Constructor called 3 times here
Destructor called 3 times here
private member function “destroy”called 4 times indirectly here
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
82
Shallow vs. Deep Copy
Assume the following:
void main () { LL list1, list2;
list1.buildLL(4);
list2 = list1;}
Constructor called -- top pointer set to NULL
Build a linked listof size 4
Shallow copy of list1made to list2
Destructor called for both list1 and list2
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
83
Shallow vs. Deep Copy
void main () { LL list1;
list1.buildLL(4);
LL list2 = list1;}
A shallow copy in this circumstance simply means that the data members of list1 are copied to the data members of list2 -- the top pointer of list1 and list2 will now point to the same place
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
84
Shallow vs. Deep Copy
void main () { LL list1;
list1.buildLL(4);
LL list2 = list1;}
Creating an alias is useful, but not likely the result you were looking for here -- reallywant a “copy” of the entire linked list
list1.top
2 4 6 8
list2.top
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
85
Shallow vs. Deep Copy
void main () { LL list1, list2;
list1.buildLL(4);
list2 = list1;}
Creating an alias is useful, but not likely the result you were looking for here -- reallywant a “copy” of the entire linked list
list1.top
2 4 6 8list2.top
2 4 6 8
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
86
Shallow vs. Deep Copy
- A deep copy implies that the actual structure is copied -- not the data members
- It is possible to write a member function that does an explicit deep copy of one linked list to another, but there are times when a deep copy would best be done implicitly
- Initialization (as in the previous example)- Passing a linked list to a function as a value parameter
- Would then be able to “protect” a linked list much as you can protect an integer
- Be cognisant of the overhead involved
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
87
Shallow vs. Deep Copy
- Returning a linked list from a function
- What problem would you currently have if you tried to return a linked list from a function?
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
88
Copy Constructor
- Implicit deep copying can be performed by creating a copy constructor
- Copy constructor is a function that will automatically be called when a deep copy is likely required
- As in the previous three cases
So...
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
89
Copy Constructor
class LL { private: NodePtr top; void copy(NodePtr, NodePtr&); // Deep copy of 1st to 2nd
void destroy(NodePtr&);
public: LL(); ~LL(); LL(const LL&); // Copy constructor void buildLL(int); void printLL(); };
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
90
void LL::copy(NodePtr atop, NodePtr& btop) {// Performs a deep copy from linked list pointed to // by “atop” to linked list pointed to be “btop”. NodePtr acurr, bcurr;
destroy (btop); // Free any storage used by target linked list if (atop != NULL) { btop = new (node); btop->number = atop->number; acurr = atop; bcurr = btop; while (acurr->next != NULL) { bcurr->next = new (node); acurr = acurr->next; bcurr = bcurr->next; bcurr->number = acurr->number; } bcurr->next = NULL; }
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
91
Copy Constructor
LL::LL(const LL& source) { // Copy constructor -- does a deep copy of linked list.
copy (source.top, top);}
<See: Example 2>
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
92
Doubly Link List
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
93
Header Nodes
- Special cases exist with linked list algorithms because the “top” pointer is subject to change
- Header nodes
- A header node can be placed at the front of a linked list to eliminate special cases
- Sometimes called a dummy node
- A empty list will now consist of a “top” pointer pointing at a pre-allocated header node
- Header node exists simply to avoid ever having to modify “top” pointer
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
94
Header Nodes
Creation of header node would be part of the linked list constructor:
LL::LL() { // Linked list constructor
top = new node; top -> number = 0; // This number will never be processed top -> next = NULL;}
Data component of header node could also be used to hold list related data such as the number of nodes in the list
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
95
Header Nodes
- An insert or remove function would now
only have to worry about the general case:
void LL::insertLL(int item) {
prev = top; curr = top -> next;
newnode = new node; newnode -> number = item; newnode -> next = curr; prev -> next = newnode;
}
••
•••
••
Would have to perform a search here if doingan ordered insert
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
96
Header Nodes
void LL::deleteLL(int item) { prev = top; curr = top -> next;
// Assume item will be found
prev -> next = curr -> next; delete curr; }
•••
•••
Would have to perform a search here to finddeletion point
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
97
Doubly Linked Lists
- Doubly linked list
- Also called back-linked lists
- Instead of a single forward link per node, an additional back link is introduced
- Bi-directional linear linked list
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
98
Doubly Linked Lists
top
27 -38 4 59
Remember (despite the diagram) that a pointer to a node points to the starting address of the node
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
99
Doubly Linked Lists
- Doubly linked list
- No local “prev” variable is required for Insert and Delete routines as it is built into each node
- For a large list, probably not a good trade-off
- Allows for better mobility
- For example, could now print the list out backwards
- Create structures to fit the data and the problem, not the other way around
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
100
Identical to linear linked list node declaration except for an additional pointer field
Doubly Linked Lists
- Declaration for doubly linked list
class node;typedef node* nodeptr;
class node { public: int number; nodeptr next; nodeptr prev; };
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
101
Doubly Linked Lists
- Using a back-linked list is a trade-off
- Some things easier to do as a result of increased flexibility of the structure
- Some things harder to do as a result of twice the pointer fields
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
102
Doubly Linked Lists
curr -> prev -> next = curr -> next;
curr -> next -> prev = curr -> prev;
delete curr;
•••
•••
Assumes the existenceof a header node and thatitem to be deleted will be found
Removing a node from a doubly-linked list
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
103
Doubly Linked Lists
27 -38 4 59
top
curr
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
104
Doubly Linked Lists
27 -38 4 59
top
curr
curr -> prev -> next = curr -> next;
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
105
Doubly Linked Lists
27 -38 4 59
top
curr
curr -> next -> prev = curr -> prev;
curr -> prev -> next = curr -> next;
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page
106
Doubly Linked Lists
27 -38 59
top
delete curr;
curr -> next -> prev = curr -> prev;
curr -> prev -> next = curr -> next;