Recitation #1
description
Transcript of Recitation #1
RECİTATİON #1Pointer Basics
by Müge Birlik
PASS-BY-VALUE If you change the value of a parameter in function,
corresponding argument does NOT change in the caller function. Function works on the copy of the variable
void square(int a) { a = a*a; } int main() { int num = 5; cout << "Before calling square function: num=" << num << endl; square(num); cout << "After calling square function: num=" << num << endl; return 0; }
Before calling square function: num=5 After calling square function: num=5
2
PASS-BY-VALUE
One way to change the value of the parameter in the calling function is the following
int square(int a) { a = a*a; return a; } int main() { int num = 5; cout << "Before calling square function: num=" << num << endl; num = square(num); cout << "After calling square function: num=" << num << endl; return 0; }
Before calling square function: num=5 After calling square function: num=25
3
PASS-BY-REFERENCE If you change the value of a reference parameter
in function, corresponding argument changes in the caller function. Function works on the actual variable, not on the copy
void square(int &a) { a = a*a; } int main() { int num = 5; cout << "Before calling square function: num=" << num << endl; square(num); cout << "After calling square function: num=" << num << endl; return 0; }
Before calling square function: num=5 After calling square function: num=25
4
UNDERLYİNG MECHANİSMS
For value parameters, the arguments’ values are copied into parameters. Arguments and parameters have different
memory locations.
void square(int a)
int main() {
………
square(num);
………
}
5
5
Copy value of argument
5
UNDERLYİNG MECHANİSMS
For reference parameters, the parameter and the argument share the same memory location Parameter is an alias of the argument.
void square(int &a)
int main() {
………
square(num);
………
}
5
Refers to the same memory location
6
INTRODUCİNG CONST
Why do we use const? Guarantees safety of variable values.
const assures that the value of the variable will not be changed.
prevents accidental changes in the values of the variables.
! error C3892: 'pi' : you cannot assign to a variable that is const
void calculate_area(double radius, const double pi, double &result) { pi = 3; result = radius * radius * pi; } int main() { double r = 2; const double pi = 3.14; double area = 0; calculate_area(r,pi,area); cout << area << endl; return 0; } 7
INTRODUCİNG CONST
Why do we use const reference? For efficiency.
For parameters that require a large amount of memory, making the copy takes time in addition to memory used for the copy. Reference parameters are not copied, and thus no
extra memory is required, and less time is used. So, use const reference if
the parameter require large amount of memory the value of the parameter will never be changed in
the function
8
POİNTER BASİCS
WHY DO WE NEED POİNTERS?
Pointers allow different sections of the code to share
information easily. form the basis for implementing complex linked
data structures, such as linked lists and binary trees.
10
WHAT İS A POİNTER? Pointers are variables that store an address in
computer memory. This way, they simply store a reference to a
variable. a pointer points to a dynamically allocated
memory location (variable), not an ordinary variable.
Lifetime of an ordinary variable is limited within its scope The code block in which it is defined After the block finishes, the variable returns back to the
memory However, the lifetime of a dynamically allocated
variable depends on the programmer. Special functions are used to allocate and free such
variables; namely new and delete.
11
REPRESENTATİON OF A POİNTER
.
.
.
.
0
numPtr
num
42
A simple int variable. The current value is the integer 42. This variable also plays the role of pointee for the pointer below.
A pointer variable. The current value is a reference to the pointee num above (address).
1
2
3
4
5
6
1
int num; int *numPtr; num = 42; numPtr = #// Compute a reference
// to "num", and store // it in numPtr.
// At this point, // memory looks like // the drawing
12
SYNTAX OF POİNTERS
Pointer decleration: type *variable_name;
Pointer variable is defined as a pointer having type of type.
Pointer variable holds the address of a memory location that holds a type value.
13
SYNTAX OF POİNTERS
Dynamic memory allocation using new type *variable_name = new type;
allocates enough memory from heap (a special part of memory reserved for dynamic allocation) to store a type value.
returns the address of this memory location. assign this address to a pointer variable for further
processing. If type is a class, then class constructor is also invoked.
double *ptr; //a pointer for double type, but currently points nowhere. ptr = new double; //memory is allocated to store a double value, but //currently not initialized. ptr now points to that
//location.
14
SYNTAX OF POİNTERS
You can have pointers for any type Primitive types (int, double, char,…) Built-in or user defined types, classes and structs
(string, dice, date, …) Similarly, you can dynamically allocate
memory for any type using the keyword new.
myClass *classPtr; classPtr = new myClass; //dynamically allocates enough memory for //a myClass object, and stores the address in //classPtr. //this allocation automatically invokes the //class constructor.
15
SYNTAX OF POİNTERS
Example (pointer definition for the Date class)
a new Date object is created with value February 23, 2010 and date_ptr points to it.
Example (pointer definition for vector class)
a vector with 10 integer pointers, currently points nowhere.
Date *date_ptr = new Date(02, 23, 2010);
February 23, 2010date_ptr
tvector <int *> intptrs(10);
16
CAREFUL WİTH NEW
What is the problem with the following code segment?
Error message: address of local variable returned! Returning a pointer to a statically allocated variable
(with the & operator), is wrong! nSided no longer exists after the function returns.
Dice * MakeDice(int n) //return pointer to n sided object { Dice nSided(n); return &nSided; } Dice *cube = MakeDice(4); Dice *tetra = MakeDice(6); cout << cube->NumSides();
17
CAREFUL WİTH NEW
Correct version Dice * MakeDice(int n) //return pointer to n sided object { Dice * nSided_ptr = new Dice(n);
return nSided_ptr; } Dice *cube = MakeDice(4); Dice *tetra = MakeDice(6); cout << cube->NumSides();
18
SYNTAX OF POİNTERS
Memory deallocation using delete delete variable_name;
the memory location pointed by variable_name is returned back to the heap.
this area now may be reallocated with a new statement.
Problem: variable_name still points to the same location, but that location is no longer used. may cause confusion, so it may be a good idea to
reset the pointer to NULL (zero) after deleting. e.g. p = NULL; NULL is a standard constant that you can directly use in
your programs a NULL pointer means that it points nothing.
19
SYNTAX OF POİNTERS
You can only deallocate the memory spaces that have been dynamically allocated using new statement. Others (ordinary variables) are handled by the
runtime system of the programming language. If you attempt to delete such a memory chuck,
you will get core-dumped.
Date *p1 = new Date(); Date *p3 = new Date(29,2,2003); ... delete p1; //We need to delete memory allocated with new delete p3;
20
PROBLEMS İN DEALLOCATİON
Careful ! deleting previously deallocated memory causes a
crash. Question
Do we need to delete p_temp? No. It points to a statically allocated (stack) variable.
What happens if we delete? Most likely a crash or corrupt program, depending on
the compiler.
int n; int *p_temp = &n;
21
PROBLEMS İN DEALLOCATİON: MEMORY LEAK Memory is not unlimited, make sure that you
deallocate what you allocated Memory leak occurs when a computer
program consumes memory but is unable to release it back to the operating system
22
void pow(int x) { int *num = new int; *num = x * x; cout << x << "^2 = " << *num << endl; } int main() { for (int i=0;i<1000;i++) { pow(i); } }
PROBLEMS İN DEALLOCATİON: DANGLİNG PTR If multiple pointers point to same variable and
one of them is deallocated, then rest of the pointers point to unallocated space.
If you deallocate memory that a pointer points to, then it's pointing to garbage.
Results are unpredictable Segmentation fault Returns garbage value
23
int *p, *q; p = new int; *p = 3; q = p; cout << "p=" << p << endl; delete p; cout << "q=" << q << endl;
SYNTAX OF POİNTERS
Pointer dereference (follow the pointer) *variable_name To access the content/value of the memory
location pointed by variable_name.
int num; int *numPtr; num = 42; numPtr = # cout << *numPtr << endl; //Prints the value of the variable pointed by
//numPtr, which is 42.
24
SYNTAX OF POİNTERS
The only restriction is that the pointer must point to some accessible memory location for the dereference operation to work.
//WRONG: p does not point anything! int *p; *p = 3;
//CORRECT: p points to q. int q; int *p; p = &q; *p = 3;
25
SYNTAX OF POİNTERS
In the program, you can use dereference operator to manipulate the memory location as if it is a variable of the corresponding type. int num; int *numPtr; num = 42; numPtr = # cout << *numPtr << endl; //Prints 42 *numPtr = 138; //value of the pointed variable is
//changed to 138 cout << *numPtr << endl; //Prints 138
26
SYNTAX OF POİNTERS
Pointer assignment A pointer can be assigned to another pointer of
the same type.
numPtr
num
.
.
.
.
0
421
2
3
4
5
6
1
int num; int *numPtr; num = 42; numPtr = # int *numPtr2; numPtr2 = numPtr; //numPtr2 and //numPtr point //to the same //memory location.
1 numPtr2
27
SYNTAX OF POİNTERS
Some issues regarding pointer assignment What happens if you try to assign a string/int/double
expression to a pointer variable? e.g. what about numPtr = 123.45; ?
syntax error What happens if you try to access a memory location
pointed by a pointer that is not initialized? e.g. what about the following?
a run-time (application) error occurs What happens if you display the value of a pointer?
it displays the address
double *q; cout << *q << endl;
28
EXAMPLES double *p; //a pointer is created for double type, but currently //points nowhere p = new double; //memory is allocated to store a double value, but //currently not initialized. p now points to that location *p = 17.5; //memory location pointed by p contains 17.5 cout << "memory location at address " << p << " contains " << *p << endl; double *q; q = p; //q points to the same memory location as p cout << "memory location at address " << q << " contains " << *q << endl; *q = *p+1; cout << *q << " " << *p << endl;
memory location at address 00B92210 contains 17.5 memory location at address 00B92210 contains 17.5 18.5 18.5
29
EXAMPLES Loop to allocate memory for each index of a vector
and initialize to zero.
tvector <int *> intptrs(10);//vector with 10 integer pointers, currently //point nowhere
for (int i=0; i<10; i++) intptrs[i] = new int; //pointers now point somewhere not initialized for (int i=0; i<10; i++) *intptrs[i] = 0; //now initialized to 0 for (int i=0; i<10; i++) cout << *intptrs[i] << " "; //check if correct cout << endl;
0 0 0 0 0 0 0 0 0 0
30
EXAMPLES
31
Date today; Date *nextDay = new Date(today+1); Date *prevDay = new Date(today-1); cout << "today\t\t tomorrow\t\tyesterday" << endl; cout << today << "\t" << nextDay << "\t" << prevDay << endl; cout << today << "\t" << *nextDay << "\t" << *prevDay << endl; nextDay = prevDay; cout << today << "\t" << *nextDay << "\t" << *prevDay << endl; *prevDay += 2; cout << today << "\t" << *nextDay << "\t" << *prevDay << endl; cout << today << "\t" << nextDay << "\t" << prevDay << endl; today tomorrow yesterdayApril 13 2000 0x54490 0x544a8April 13 2000 April 14 2000 April 12 2000April 13 2000 April 12 2000 April 12 2000April 13 2000 April 14 2000 April 14 2000April 13 2000 0x544a8 0x544a8
EXAMPLES
32
cout << endl << "k\tsides\troll\tcount" << endl << endl; const int DICE_COUNT = 6; tvector<Dice *> dice(DICE_COUNT); int k; for(k=0; k<DICE_COUNT; k++) { dice[k] = new Dice(2*k+1); } for(k=0; k<DICE_COUNT; k++) { cout << k << "\t" << dice[k]->numSides() << "\t" << dice[k]->Roll() << "\t"; cout << dice[k]->NumRolls() << endl; }
k sides roll count0 1 1 1 1 3 3 12 5 2 13 7 4 14 9 1 15 11 4 1
RECİTATİON #2Advanced Pointer Stuff
STRUCTS
Used as data aggregates for an entity. Can store different types of variables/data
e.g. Student struct may contain id,name,GPA,…
Similar to classes, but everything is public do not have member functions
Mostly used for combining data for an entity into a single structure.
34
struct Student{ int id; string name; double GPA; string address; };
STRUCTS
35
struct student { unsigned int id; string name, lastname; double gpa; }; void PrintStudent (const student & stu) { cout << "Name and Lastname: \t" << stu.name << " " << stu.lastname << endl; cout << "ID: \t" << stu.id << endl; cout << "GPA: \t" << stu.gpa << endl << endl; } int main() { student s1; s1.name = "John"; s1.lastname = "Coder"; s1.id = 11523; s1.gpa = 3.66; PrintStudent(s1); return 0; }
Name and Lastname: John CoderID: 59GPA: 3.66
ARRAYS
Arrays are collections of several elements of the same type. e.g. 100 integers, 20 strings, 125 students, 12
dates, etc. Single name is given to the entire array But each element is accessed separately
a class-based version of arrays is the vector class.
Arrays are homogeneous each element of an array has the same type this type must be specified at declaration
36
ARRAYS
Items in an array are numbered those are called index numbering starts with 0 we have to use the index value
to access an element of an array Syntax for declaring an array:
type variable_name[element_count];
statically allocating an array
37
0 61023
1 100238
2 27390
3 23975
4 102974
5 5482
6 98214
7 67782
8 69821
9 67762
index
data
ARRAYS
38
int monthDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; string monthNames[13] = {"", "January", "February", "March", "April",
"May", "June", "July", "August", "September", "October","November", "December"};
for(int i=1; i <=12; i++){ cout << monthNames[i] << ", " << monthDays[i] << " days" << endl; }
January, 31 daysFebruary, 28 daysMarch, 31 daysApril, 30 daysMay, 31 daysJune, 30 daysJuly, 31 daysAugust, 31 daysSeptember, 30 daysOctober, 31 daysNovember, 30 daysDecember, 31 days
ARRAYS
To dynamically allocate an array, specify the array size in square brackets [] after the type. type * variable_name = new type
[element_count];
instead of hard-coding the size of the allocated array, you can also use a user-defined variable.
39
int * ptr = new int[20]; //dynamically allocate enough //memory for an array of 20 ints. //ptr now points to the //1st element of the array.
int size = 10; int * ptr = new int[size];
ARRAYS To delete a dynamically allocated array, you
must include a pair of empty square brackets in the delete statement, just after the delete command.
40
int size = 10; int * ptr = new int[size]; ………… delete []ptr; //Use [] -no matter how many dimensions
BE CAREFUL WHİLE USİNG NEW!
If there is not enough memory that can be allocated, then NULL pointer is returned. So, check whether the pointer is NULL or not
after allocating.
41
int * ptr; ptr = new int [100000]; if (ptr != NULL){ ………………
2D ARRAYS
Most common multidimensional array type Used to store data that is normally
represented in a table format are homogeneous, similar to 1D arrays
42
2D ARRAYS
Static allocation of 2D arrays Syntax for declaration
type variable_name[row_count][column_count];
Accessing elements of a 2D array: variable_name[index1][index2];
43
char ticTacToeBoard[3][3] = {{'x', 'x', 'o'}, {'o', 'o', 'x'}, {'x', 'o', ' '} };
for (int index1=0; index1<3; index1++) { for (int index2=0; index2<3; index2++) {
cout << ticTacToeBoard[index1][index2] << " "; }
cout << endl; }
x x oo o xx o
2D ARRAYS
Dynamic allocation of 2D arrays Syntax for declaration
type ** variable_name; Memory allocation
allocate memory for an array which contains a set of pointers
next, allocate memory for each array which is pointed by the pointers
44
int **dynamicArray; //declare the 2D pointer dynamicArray = new int *[row_count]; //allocate memory for elements of rows. for( int i = 0; i < row_count; i++ ){ //allocate memory for elements of each column.
dynamicArray[i] = new int[column_count]; }
2D ARRAYS
45
int **dynamicArray; //declare the 2D pointer dynamicArray = new int *[row_count]; //allocate memory for elements of rows. for( int i = 0; i < row_count; i++ ){ //allocate memory for elements of each column.
dynamicArray[i] = new int[column_count]; }
dynamicArray
X
2D ARRAYS
46
int **dynamicArray; //declare the 2D pointer dynamicArray = new int *[row_count]; //allocate memory for elements of rows. for( int i = 0; i < row_count; i++ ){ //allocate memory for elements of each column.
dynamicArray[i] = new int[column_count]; }
dynamicArray
X X X X X
2D ARRAYS
47
int **dynamicArray; //declare the 2D pointer dynamicArray = new int *[row_count]; //allocate memory for elements of rows. for( int i = 0; i < row_count; i++ ){ //allocate memory for elements of each column.
dynamicArray[i] = new int[column_count]; }
dynamicArray
2D ARRAYS
Deallocation of dynamically allocated 2D arrays Performed in reverse order
48
for( int i = 0; i < row_count; i++ ) { delete [] dynamicArray[i];
} delete [] dynamicArray ;
2D ARRAYS
49
for( int i = 0; i < row_count; i++ ) { delete [] dynamicArray[i];
} delete [] dynamicArray ;
dynamicArray
2D ARRAYS
50
for( int i = 0; i < row_count; i++ ) { delete [] dynamicArray[i];
} delete [] dynamicArray ;
dynamicArray
X X X X X
2D ARRAYS
51
for( int i = 0; i < row_count; i++ ) { delete [] dynamicArray[i];
} delete [] dynamicArray ;
dynamicArray
X
2D ARRAYS
52
#include <iostream> using namespace std; void print_table(int** values, int num_rows, int num_cols) { int i, j; for (i = 0; i < num_rows; i++) { for (j= 0 ; j< num_cols ; j++) cout << values[i][j] << " "; cout << endl; } } int main() { int **nums; int rows, columns, i, j; cout << "Enter the number of rows: "; cin >> rows; cout << "Enter the number of columns: "; cin >> columns;
//nums is an array of int pointers nums = new int*[rows]; //each nums[i] is an array of ints. for(i = 0; i<rows; i++) nums[i] = new int[columns]; cout << "Enter the elements" << endl; for(i = 0; i < rows; i++) { for(j= 0 ; j< columns ; j++) { cout << '[' << i << ',' << j << "]: "; cin >> nums[i][j]; cout << endl; } } print_table(nums, rows, columns); // Returning memory to free heap for reuse for (i = 0; i< rows; i++) delete [] nums[i]; delete [] nums; }
POİNTER ARİTHMETİC If you increment a pointer, it will be
increased by the size of whatever it points to. Example
in this case the pointer points to 4 bytes ahead to the next integer (note: integer is 4bytes long) 53
int students[10]; int *ptr; ptr = students; //ptr points to students[0] ptr = &students[0]; //same as above ptr++; //ptr now points to students[1] int *p_tmp; p_tmp = ptr; //p_tmp also points to students[1]
POİNTER ARİTHMETİC
QUESTION: What happens if you try to access *(ptr+10) ? You will get segmentation fault !
This memory location is not allocated.
54
int students[10]; int *ptr; ptr = students; //ptr points to students[0]
s[0]
s[1]
s[2]
s[3]
s[4]
s[5]
S[6]
s[7]
s[8]
s[9]
*ptr
*(ptr+2)
*(ptr+9)
POİNTER ARİTHMETİC
55
char c = ‘c’; char *p; //p points nowhere p = &c; // p now points to c. p--; // p now points to the address of the BYTE before c p++; // p points to c again.
const int NUM_STUDENTS = 10; int students[NUM_STUDENTS]; int *ptr; ptr = students; // address stored in pointer is that of
//the first element in array
for (i=0; i < NUM_STUDENTS; i++) cout << students[i]; for (i=0; i < NUM_STUDENTS; i++) cout << *ptr++;
2nd one is often much more efficient !!
-incrementing is faster than addition
-also when array indexing is more complex
(with more complicated offsets...),
pointers are even more efficient
LİNKED LİSTS A linked list is a data structure that consists
of nodes pointing to one another. Nodes can be represented using structs.
56
A1 A2 A3 A4
struct node //node is a user given name { string word; int num; node *next; //pointer for the next node };
LİNKED LİSTS: İNSERTİNG A NEW NODE
Note that you should normally have a constructor for the struct; this is for illustration of the pointer usage.
57
node *p; p = new node; p->num = 5; p->word = "Ali"; p->next = NULL;
5 Ali
num
word
next
p
LİNKED LİSTS: İNSERTİNG A NEW NODE
Let’s add a new node to our linked list
58
5 Ali
num
word
next
p
q
?
node *p; p = new node; p->num = 5; p->word = "Ali"; p->next = NULL;
node *q; q = new node; q->num = 8; q->word = "Veli"; q->next = NULL; p->next = q;
LİNKED LİSTS: İNSERTİNG A NEW NODE
Let’s add a new node to our linked list
59
5 Ali
num
word
next
p
q
? ?
num
word
next
?
node *p; p = new node; p->num = 5; p->word = "Ali"; p->next = NULL;
node *q; q = new node; q->num = 8; q->word = "Veli"; q->next = NULL; p->next = q;
LİNKED LİSTS: İNSERTİNG A NEW NODE
Let’s add a new node to our linked list
60
5 Ali
num
word
next
p
q
8 Veli
num
word
next
?
node *p; p = new node; p->num = 5; p->word = "Ali"; p->next = NULL;
node *q; q = new node; q->num = 8; q->word = "Veli"; q->next = NULL; p->next = q;
LİNKED LİSTS: İNSERTİNG A NEW NODE
Let’s add a new node to our linked list
61
node *p; p = new node; p->num = 5; p->word = "Ali"; p->next = NULL;
node *q; q = new node; q->num = 8; q->word = "Veli"; q->next = NULL; p->next = q;
5 Ali
num
word
next
p
q
8 Veli
num
word
next
LİNKED LİSTS: İTERATİNG OVER A LİNKED LİST
62
We use a temporary pointer to iterate over the list At each iteration, we set the temporary pointer to
the next node We continue until there is no node left
our temporary pointer becomes NULL
5 Ali
num
word
next
p 8 Veli
num
word
next
17 Ayşe
num
word
next
node *iter; iter = p; while (iter != NULL) { cout << iter->num << " " << iter->word << endl; iter = iter->next; }
LİNKED LİSTS: İTERATİNG OVER A LİNKED LİST
63
5 Ali
num
word
next
p 8 Veli
num
word
next
17 Ayşe
num
word
next
node *iter; iter = p; while (iter != NULL) { cout << iter->num << " " << iter->word << endl; iter = iter->next; }
iter
LİNKED LİSTS: İTERATİNG OVER A LİNKED LİST
64
5 Ali
num
word
next
p 8 Veli
num
word
next
17 Ayşe
num
word
next
node *iter; iter = p; while (iter != NULL) { cout << iter->num << " " << iter->word << endl; iter = iter->next; }
iter
LİNKED LİSTS: İTERATİNG OVER A LİNKED LİST
65
5 Ali
num
word
next
p 8 Veli
num
word
next
17 Ayşe
num
word
next
node *iter; iter = p; while (iter != NULL) { cout << iter->num << " " << iter->word << endl; iter = iter->next; }
iter
5 Ali
LİNKED LİSTS: İTERATİNG OVER A LİNKED LİST
66
5 Ali
num
word
next
p 8 Veli
num
word
next
17 Ayşe
num
word
next
node *iter; iter = p; while (iter != NULL) { cout << iter->num << " " << iter->word << endl; iter = iter->next; }
iter
5 Ali
LİNKED LİSTS: İTERATİNG OVER A LİNKED LİST
67
5 Ali
num
word
next
p 8 Veli
num
word
next
17 Ayşe
num
word
next
node *iter; iter = p; while (iter != NULL) { cout << iter->num << " " << iter->word << endl; iter = iter->next; }
iter
5 Ali
LİNKED LİSTS: İTERATİNG OVER A LİNKED LİST
68
5 Ali
num
word
next
p 8 Veli
num
word
next
17 Ayşe
num
word
next
node *iter; iter = p; while (iter != NULL) { cout << iter->num << " " << iter->word << endl; iter = iter->next; }
iter
5 Ali8 Veli
LİNKED LİSTS: İTERATİNG OVER A LİNKED LİST
69
5 Ali
num
word
next
p 8 Veli
num
word
next
17 Ayşe
num
word
next
node *iter; iter = p; while (iter != NULL) { cout << iter->num << " " << iter->word << endl; iter = iter->next; }
iter
5 Ali8 Veli
LİNKED LİSTS: İTERATİNG OVER A LİNKED LİST
70
5 Ali
num
word
next
p 8 Veli
num
word
next
17 Ayşe
num
word
next
node *iter; iter = p; while (iter != NULL) { cout << iter->num << " " << iter->word << endl; iter = iter->next; }
iter
5 Ali8 Veli
LİNKED LİSTS: İTERATİNG OVER A LİNKED LİST
71
5 Ali
num
word
next
p 8 Veli
num
word
next
17 Ayşe
num
word
next
node *iter; iter = p; while (iter != NULL) { cout << iter->num << " " << iter->word << endl; iter = iter->next; }
iter
5 Ali8 Veli17 Ayşe
LİNKED LİSTS: İTERATİNG OVER A LİNKED LİST
72
5 Ali
num
word
next
p 8 Veli
num
word
next
17 Ayşe
num
word
next
node *iter; iter = p; while (iter != NULL) { cout << iter->num << " " << iter->word << endl; iter = iter->next; }
iter
5 Ali8 Veli17 Ayşe
LİNKED LİSTS: İTERATİNG OVER A LİNKED LİST
73
5 Ali
num
word
next
p 8 Veli
num
word
next
17 Ayşe
num
word
next
node *iter; iter = p; while (iter != NULL) { cout << iter->num << " " << iter->word << endl; iter = iter->next; }
iter
5 Ali8 Veli17 Ayşe
LİNKED LİSTS: İTERATİNG OVER A LİNKED LİST
74
5 Ali
num
word
next
p 8 Veli
num
word
next
17 Ayşe
num
word
next
node *iter; iter = p; while (iter != NULL) { cout << iter->num << " " << iter->word << endl; iter = iter->next; }
iter
5 Ali8 Veli17 Ayşe
LİNKED LİSTS: REMOVİNG THE LİST
75
//recursive void RemoveList(node *p) { if (p != NULL) { RemoveList(p->next); delete p; } } //iterative void RemoveList(node *p) { node *temp; while (p != NULL) { temp = p->next; delete p; p = temp; } }
As linked list is allocated dynamically, it should be removed afterwards
It is similar to iteration, but instead of printing out we remove each node using delete statement.
Thanks to Albert Levi and Berrin Yanıkoğlu
76