Upload
shussein
View
231
Download
0
Embed Size (px)
Citation preview
7/29/2019 Pds Fall2003
1/52
The College of TechnologyComputer Technology Department
PROGRAMMING AND DATA STRUCTURES
COURSE NOTES
FALL 2003
Dr. Sayed A. Hussein
7/29/2019 Pds Fall2003
2/52
C O N T E N T S
CHAPTER(1) FUNDAMENTALS .......................................................................................................... ........................ 1
1.1 DATATYPES ............................................................................................................ .............................................. 11.2 FUNCTIONS................................................................................................................................................................ 21.3 FORMATTING OUTPUT...................................................... ................................................................. ........................ 3
CHAPTER(2) ARRAYS AND STRINGS .................................................................................................................. ..... 42.1 ARRAYS OF STRUCTURES ............................................................ ................................................................. ............. 52.2 STRUCTURES AND ARRAYS ......................................................... ................................................................. ............. 62.3 ARRAYS AS CLASS MEMBERDATA........................................................ .............................................................. ..... 72.4 ARRAYS OF OBJECTS ........................................................ ................................................................. ........................ 82.5 STRINGS .................................................................................................................................................................... 92.6 ARRAY SEARCHING................................................................................................................................................. 102.6.1 Linear Search Algorithm ............................................................. ................................................................. ........... 102.6.2 Binary Search Algorithm ...................................... ................................................................. ................................. 112.7 SORTING ARRAYS ................................................................................................................................................... 112.7.1 Selection Sort .............................................................................. .............................................................. .............. 112.7.2 Insertion Sort .......................................................................................................................................................... 122.7.3 Bubble Sort.............................................................................................................................................................. 122.7.4 Quicksort ............................................................... ................................................................. ................................. 13
CHAPTER(3) STACKS AND QUEUES ................................................................ ....................................................... 15
3.1 STACKS ................................................................................................................................................................... 153.1.1 Introduction to Stacks ................................ ................................................................. ............................................ 153.1.2 Evaluation of Arithmetic Expressions ....................................................................................................... .............. 163.1.3 Array Implementation of the Stack ......................................................... .............................................................. ... 183.2 FIFOQUEUES ......................................................................................................................................................... 203.2.1 Introduction to Queues............................................................................................................................................ 203.2.2 Array Implementation of a FIFO Queue .......................................................... ....................................................... 21
CHAPTER(4) POINTERS ...................................................................................... ....................................................... 23
4.1
WHAT IS A POINTER? ....................................................................................... ....................................................... 234.2 CREATING A POINTER.............................................................................................................................................. 23
4.3 USING POINTERS ..................................................................................................................................................... 254.4 POINTERS AND STRUCTURES ................................................................. ............................................................... ... 274.5 POINTERS AND OBJECTS .............................................................. ................................................................. ........... 294.5.1 Declaration and Access .......................................................................................................................................... 294.5.2 An array of Pointers to Objects .............................................................................................................................. 294.6 POINTERS AND FUNCTION ARGUMENTS ........................................................... ....................................................... 304.7 POINTERS AND ARRAYS .............................................................. ................................................................. ........... 324.8 POINTERARITHMETIC ............................................................................................................................................. 334.9 DYNAMIC MEMORY ALLOCATION (NEW, DELETE) ............................................................................ ...................... 354.9.1 The new Operator ................................................. ................................................................. ................................. 354.9.2 The delete Operator ................................................................... ............................................................... .............. 35
4.9.3 Dynamic Arrays ............................................................... ................................................................. ...................... 36CHAPTER(5) FILE INPUT/OUTPUT ........................................................ .............................................................. ... 37
5.1 DISKFILE I/O WITH STREAMS ................................................................ ................................................................ . 375.2 FORMATTED FILE I/O .................................................................................................. ............................................ 375.2.1 Writing data ..................................................................... .............................................................. ......................... 375.2.2 Reading Data .............................................................................. .............................................................. .............. 385.2.3 Character I/O ........................................................ ................................................................. ................................. 395.3 BINARY I/O ...................................................................................................... ....................................................... 40
CHAPTER(6) LINKED LISTS .......................................................... ................................................................. ........... 43
6.1 INTRODUCTION........................................................................................................................................................ 436.2 CREATING A LINKED LIST ........................................................... ................................................................. ........... 43
6.3 DELETING A NODE FROM A LINKED LIST ........................................................... ....................................................... 446.4 ADDING NODES TO A LINKED LIST (INSERTING A NODE) ............................................................................ .............. 446.5 TRAVERSING A LINKED LIST ........................................................ ................................................................. ........... 456.6 WORKING WITH DYNAMICALLY CREATEDNODES ................................................................. ................................. 466.7 ALINKED LIST EXAMPLE............................................................. ................................................................. ........... 48
7/29/2019 Pds Fall2003
3/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 1
CHAPTER(1)
FUNDAMENTALS
1.1 DATA TYPES
A data type is a set ofvalues and a collection ofoperations on those values. All the data thatwe process on a computer ultimately decompose into individual bits, but writing programs thatprocess bits would be tiresome indeed. Types allow us to specify how we will use particularsets of bits and functions allow us to specify the operations that we will perform on the data.The four basic data types in C++ are
INTEGERThese are whole numbers, both positive and negative. Unsigned integers (positivevalues only) are supported. In addition, there are short and long integers. The keywordused to define integers is,
intAn example of an integer value is 32. An example of declaring an integer variable calledsum and assigning the value 20 to it is,
int sum;sum = 20;
To declare an integer constant we use the const keyword:
const int MaxMark=30;
In fact we can use const with all other data types, not only with integers.
FLOATING POINTThese are numbers which contain fractional parts, both positive and negative. Thekeyword used to define float variables is, floatAn example of a float value is 34.12. An example of declaring a float variable calledmoney and assigning the value 326.75 to it is,
float money;money = 326.75;
DOUBLE
These are exponential numbers, both positive and negative. The keyword used to
define double variables is double. An example of a double value is 3.0E2. An exampleof declaring a double variable called big and assigning the value 312E+27 to it is,
double big;big = 312E+27;
CHARACTERThese are single characters. The keyword used to define character variables is, char.An example of a character value is the letterA. An example of declaring a charactervariable called letterand assigning the value A to it is,
char letter;letter = 'A';
Note the assignment of the characterA to the variable letter is done by enclosing thevalue in single quotes. Remember the golden rule: for single character - use singlequotes.
7/29/2019 Pds Fall2003
4/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 2
Sample program illustrating each data type
#include int main(){ int sum, N=3;
float money, average;char letter;
double pi;
sum = 10; // assign integer valuemoney = 2.21; // assign float valueletter = 'A'; // assign character valuepi = 2.01E26; // assign a double valueaverage = ((float) sum) / N;
cout
7/29/2019 Pds Fall2003
5/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 3
(i) functions which compute and return a value;(ii) functions which simply carry out some task without returninga specific value.
For further information on functions refer to your textbook: OOP in C++ by Robert Lafore.
1.3 Formatting Output(For further details see Lafore textbook pages 52-54, and pages 270-274.
Manipulators are operators used with the insertion operator (
7/29/2019 Pds Fall2003
6/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 4
CHAPTER(2)
ARRAYS AND STRINGS
The term data structure refers to a mechanism for organizing information to provide convenient
and efficient mechanisms for accessing and manipulating it. The most fundamental datastructure is the array, which is defined as a primitive type in C++ and in most otherprogramming languages. The array is a linear data structure. An array is a fixed collection ofsame-type data that are stored contiguously and that are accessible by an index or asubscript. For example:
int a[10]; //array a has 10 integer elements.int b[]={21,8,20,14,24,29,12}; //array b is initialized with the shown numbers.char str[]=The quick brown fox jumped over the lazy dogs; //null-terminated string.
We can also use two-dimensional arrays. The following examples show how to declare andinitialize two-dimensional array.
Example1:A two-dimensional array b[2] [2] is initialized: int b[2] [2] = {{1,2},{3,4}};which means element b[0] [0]= 1, b[0] [1]= 2, b[1] [0]= 3 and b[1] [1]= 4
Example 2:
// displays sales chart, initializes 2-d array#include #include //for setprecision, etc.
const int DISTRICTS = 4; //array dimensionsconst int MONTHS = 3;
int main(){int d, m;
//initialize array elementsdouble sales[DISTRICTS][MONTHS]
= { { 1432.07, 234.50, 654.01 },{ 322.00, 13838.32, 17589.88 },{ 9328.34, 934.00, 4492.30 },{ 12838.29, 2332.63, 32.93 } };
cout
7/29/2019 Pds Fall2003
7/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 5
2.1 Arrays of Structures
Arrays can contain structures as well as simple data types. Consider the following structure,
struct date {int month, day, year;};
Let us now create an array called birthdays of the same data type as the structure date
date birthdays[6];
This creates an array of 6 elements which have the structure ofdate. We may assign values tothe second element of the array as:
birthdays[1].month = 3;birthdays[1].day = 8;birthdays[1].year = 1992;
Or we may initialize the array birthdays as follows:
date birthdays[6] = { {8, 14, 1989}, {3, 8, 1992},
{10, 12, 1994}, {9, 29, 1996},{6, 20, 1999}, {6, 10, 2002}};
Example:// Demonstrates using arrays of structures.
#include
int main(){
// Define a structure to hold entries.struct entry {
char fname[20];char lname[20];
char phone[10];};
// Declare an array of structures.entry list[4];
int i;
// Loop to input data for four people.
for (i = 0; i < 4; i++){
coutlist[i].fname;
coutlist[i].lname;coutlist[i].phone;
}
// Print two blank lines.cout
7/29/2019 Pds Fall2003
8/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 6
Program input/output example
Enter first name: SalimEnter last name:AhmedEnter phone in 123-4567 format: 555-1212Enter first name: SamiaEnter last name: IbrahimEnter phone in 123-4567 format: 555-3434
Enter first name:NasirEnter last name:AbdallaEnter phone in 123-4567 format: 555-1212Enter first name: HananEnter last name:AdamEnter phone in 123-4567 format: 555-1234Name: Salim Ahmed Phone: 555-1212Name: Samia Ibrahim Phone: 555-3434Name: Nasir Abdalla Phone: 555-1212Name: Hanan Adam Phone: 555-1234
2.2 Structures and Arrays
Example1:You can define a structure that contains one or more arrays as members. The array can be ofany C++ data type (int, char, and so on). For example, the statements
struct data{int x[4];char y[10];
};
define a structure of type data that contains a four-element integer array member named x anda 10-element character array member named y. You can then declare a structure namedrecord of type data as follows:
data record;
The organization of this structure is shown in the figure below. Note that the elements of arrayx take up twice as much space as the elements of array y. This is because a type int typicallyrequires two bytes of storage, whereas a type char usually requires only one byte.
You access individual elements of arrays that are structure members using a combination ofthe member operator and array subscripts:
record.x[2] = 100;record.y[1] = x;
Here is another example:
record.x[0] record.x[3] record.y[9]
Record.y[6]The organization of a structure that contains arrays as members.
7/29/2019 Pds Fall2003
9/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 7
struct month {int number_of_days;char name[4];
};
month this_month = { 31, "Jan" };
this_month.number_of_days = 31;
strcpy( this_month.name, "Jan" );cout
7/29/2019 Pds Fall2003
10/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 8
if(m
7/29/2019 Pds Fall2003
11/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 9
cout
7/29/2019 Pds Fall2003
12/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 10
< 0 ifS1 is less than S2== 0 ifS1 the same as S2
> 0 ifS1 is greater than S2.
Example:
cout
7/29/2019 Pds Fall2003
13/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 11
2.6.2 Binary Search Algorithm
A more efficient search method for ordered arrays is given in the following function. Thismethod is called the binary search method. The process compares element v with the middleelement of the array, and returns successfully if the values match. If v is less than the middleelement then the search is conducted only in the left half of the array. If it is greater then thesearch is made in the right half of the array. Now v is compared with the middle element of the
subarray and the process is repeated till a value is found or a1 is returned.
int search(int a[], int v, int l, int r){
while (r >= l){ int m = (l+r)/2;if (v == a[m]) return m;if (v < a[m])
r = m-1;else
l = m+1;}
return -1;
}2.7 Sorting Arrays
2.7.1 Selection Sort
One of the simplest sorting algorithms works as follows:
First, find the smallest element in the array, and exchange it with the element in thefirst position.
Then, find the second smallest element and exchange it with the element in thesecond position.
Continue in this way until the array is sorted.
This method is called selection sort because it works by repeatedly selecting the smallestremaining element.
#include #include
void exch(int &x, int &y);void selection(int a[], int l, int r);
int main(){int t, x[100];
randomize();
for (int i=0; i
7/29/2019 Pds Fall2003
14/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 12
void exch(int &x, int &y){
int temp=x;x=y;y=temp;
}
2.7.2 Insertion Sort
In this sort method we find the smallest element and insert it in its appropriate position. Weneed to make space for the element being inserted by moving larger elements to the right, andthen inserting the element into the vacated position.
#include #include void exch(int &A, int &B){ int t = A; A = B; B = t; }
void compexch(int &A, int &B)
{ if (B < A) exch(A, B); }void insertion(int a[], int l, int r){ for (int i = l+1; i l; j--)compexch(a[j-1], a[j]);
}int main(int argc, char *argv[]){ int i, N = atoi(argv[1]),
sw = atoi(argv[2]);int *a = new int[N];if (sw)
for (i = 0; i < N; i++)a[i] = 1000*(1.0*rand()/RAND_MAX);else{ N = 0; while (cin >> a[N]) N++; }
insertion(a, 0, N-1);for (i = 0; i < N; i++) cout
7/29/2019 Pds Fall2003
15/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 13
#include #include
void exch(int &x, int &y);void compexch(int &A, int &B);void bubble(int a[], int l, int r);int main()
{int t, x[100];
randomize();
for (int i=0; i
7/29/2019 Pds Fall2003
16/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 14
#include #include
int partition(int a[], int l, int r);void exch(int &x, int &y);void quicksort(int a[], int l, int r);
int main(){
int t, x[100];
randomize();
for (int i=0; i
7/29/2019 Pds Fall2003
17/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 15
CHAPTER(3)
STACKS AND QUEUES
3.1 Stacks3.1.1 Introduction to Stacks
Stacks: Piles of objects of any kind;Add/Remove objects only at the top of the pile (LIFO).
A common computer data structure is the stack. The stack is a linear data structure. By linear
we mean a collection of components arranged in a straight line in which we restrict places where onecan add/remove. A stack works like the spring-loaded devices that hold trays in cafeterias.When a tray is put on top, the stack sinks down a little; when you take a tray off, it pops up.The last tray placed on the stack is always the first tray removed. This is called Last-In-First-Outdiscipline (LIFO).
Stacks are one of the cornerstones of the architecture of the microprocessors used in mostmodern computers. Functions pass their arguments and store their return addresses on thestack. This kind of stack is implemented partly in hardware and is most conveniently accessedin assembly language. However stacks can be created completely in software. Softwarestacks offer a useful storage device in certain programming situations, such as parsing
(analyzing) algebraic expressions.A stack comprises two basic operations: push a new item (i.e. add or inserta new item), andpop the item that was most recently pushed (i.e. remove it).
Spring-loaded pile:
Add/Remove objects only at the top of the pile.
Only the top of the pile is accessible.
The top remains in a fixed position.
Pushing and popping are inverse operations: Push object and immediately afterwards pop it. Original stack remains unchanged.
Adding a new object to the top:pushingit onto the stack.
Adding a new object to the
top: pushingit onto the stack.Removing an object from the top:
poppingit from the stack.
7/29/2019 Pds Fall2003
18/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 16
The figure below shows how a sample stack evolves through a series of push and popoperations. Each push increases the size of the stack by 1 and each pop decreases it by 1.
F igur e (S1):This list shows the result of the sequence
of operations in the left column (top to
bottom), where a letter denotes push andan asterisk denotes pop. Each line
displays the operation, letter popped for
pop operations, and the contents of the
stack after the operations, in order from
least recently inserted to most recently
inserted, left to right.
LA*STI
*N*FIR*ST**OU*T
*******
A
I
N
R
TS
U
TOIFTSL
LL ALL SL S TL S T I
L S TL S T NL S TL S T FL S T F IL S T F I RL S T F IL S T F I SL S T F I S TL S T F I SL S T F IL S T F I OL S T F I O UL S T F I OL S T F I O T
L S T F I OL S T F IL S T FL S TL SL
Exercises:1. A letter means push and an asterisk means pop in the sequence
E A S * Y * Q U E * * * S T * * * I O * N * * *.Give the sequence of values returned by the pop operations.
2. Using the conventions of exercise 1, give a way to insert asterisks in the sequenceE A S Y so that the sequence of values returned by the pop operations is
(i) E A S Y ; (ii) Y S A E ; (iii) A S Y E ; (iv) A Y E S ; or, in each instance, prove
that no such sequence exists.
3.1.2 Evaluation of Arithmetic Expressions
We need to find the value of a simple arithmetic expression involving multiplication andaddition of integers, such as
( 5 * ( ( ( 9 + 8 ) * ( 4 * 6 ) ) + 7 ) )
This form of the arithmetic expression is called infix notation. The calculation involves savingintermediate results: For example, if we calculate 9 + 8 first, then we have to save 17 while,say, we compute 4 * 6. A stack is the ideal mechanism for saving intermediate results in suchcalculations.
To solve the above problem we convert the infix expression to postfix (where each operatorappears after its two operands). [The reverse of postfix is called prefix, or Polish notation].In postfix or prefix we do not need parentheses.
The following figure shows the steps for converting an infix expression to its post fix form. Thepostfix equivalent of the above expression is
5 9 8 + 4 6 * * 7 + *
(
7/29/2019 Pds Fall2003
19/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 17
F igur e (S2):Conversion of an Infixexpression to postfix:
This sequence shows the use of a stack to
convert the infix expression shown above
to its postfix form: 5 9 8 + 4 6 * * 7 + * .
We proceed from left to right through the
expression: If we encounter a number,
we write it to the output; if we encounter
a left parenthesis, we ignore it; if we
encounter an operator, we push it on the
stack; and if we encounter a right
parenthesis; we write the operator at the
top of the stack to the output.
5*(((9+8)
*(4*6))+7))
5
9
8+
4
6**
7+*
****** +* +*
* ** ** ** * ** * ** *** +* +*
The following program stores the postfix form of the given expression in an array called p. Ituses a class called STACK, defined as a template in a file called stack.cpp [Class templatesallow us to use different data types with one class definition-see Lafore, page 690].
#include #include #include "stack.cpp"int main()
{ char a[] = "(5*(((9+8)*(4*6))+7))";int N = strlen(a);char p[80];STACK ops;for (int i = 0, j=0; i < N; i++)
{if (a[i] == ')')
{p[j++]=ops.pop();p[j++]=' ';}if ((a[i] == '+') || (a[i] == '*'))ops.push(a[i]);if ((a[i] >= '0') && (a[i]
7/29/2019 Pds Fall2003
20/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 18
The following program evaluates a postfix expression stored in the array a. It uses a classcalled STACK, defined as a template in a file called stack.cpp
#include #include #include "stack.cpp"int main()
{ char a[] = "5 9 8 + 4 6 * * 7 + *"; int N = strlen(a);
STACK save;for (int i = 0; i < N; i++){if (a[i] == '+')
save.push(save.pop() + save.pop());if (a[i] == '*')
save.push(save.pop() * save.pop());if ((a[i] >= '0') && (a[i] = '0') && (a[i]
7/29/2019 Pds Fall2003
21/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 19
The actual implementation of the stack data structure is given in the program below. It usesthe header file given above. By separating the implementation of the data structure from itsclients (i.e.programs that use it), we can easily change the implementation without affectingthose clients.
//file: stack.cpp#include "stack.h"
template STACK::STACK(){ N = 0; }
template int STACK::empty() const{ return N == 0; }
template void STACK::push(Item item){ s[N++] = item; }
template Item STACK::pop()
{ return s[--N]; }
ExampleThe following program show a client program using the stack ADT.
#include #include stack.cppint main(){
STACK s1;
s1.push(11);s1.push(22);
cout
7/29/2019 Pds Fall2003
22/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 20
3.2 FIFO Queues3.2.1 Introduction to QueuesThe first-in, first-out(FIFO) queue is another fundamental ADT that is similar to the stack, butuses the opposite rule to decide which element to remove. Rather than removing the mostrecently inserted element, we remove the element that has been in the queue the longest.
Buying Tickets on the Day of Play On-Site RegistrationQueues are abundant in everyday life. When we wait in line to see a movie, to register courses,or to buy groceries, we are being processed according to a FIFO discipline. Perishable items ina grocery are stored in a FIFO queue rather than in a stack. Similarly, FIFO queues arefrequently used within computer systems to hold tasks that are yet to be accomplished when wewant to provide services on a first-come, first-served basis. To summarize, FIFO queues areused forregulating the processing of tasks in a system to ensure fair treatment
Client-server systems: Clients line up to wait for service
Operating systems: Queues of tasks, e.g. print queue
Simulation and modeling: Performance analysis of systems under various loads, e.g.
air traffic control, urban transport etc.A FIFO queue is defined as an ADT that comprises two basic operations: put a new item (i.e.insert), and get the item that was least recently inserted (i.e. remove it).
F igure (Q1): A F IFO queue example
This list shows the result of the sequence
of operations in the left column (top to
bottom), where a letter denotes putand
an asterisk denotes get. Each line
displays the operation, the letter returned
forgetoperations, and the content of the
queue in order from least recentlyinserted to most recently inserted, left to
right.
FIRS*T*IN**
*FI*RS***T*OUT*
****
F
I
RS
T
I
NFI
R
S
TOUT
FF IF I RF I R SI R SI R S TR S TR S T IR S T I NS T I NT I N
I NI N FI N F IN F IN F I RN F I R SF I R SI R SR SR S TS TS T OS T O US T O U TT O U T
O U TU TT
7/29/2019 Pds Fall2003
23/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 21
3.2.2 Array Implementation of a FIFO QueueThe array representation of a FIFO queue requires that we reserve enough space for themaximum number of items expected throughout the computation. We maintain two indices intothe array: one to the beginning of the queue and one to the end of the queue. We consider thecontents of the queue to be the elements between the indices. To get an element, we removeit from the beginning (head) of the queue and increment the heads index; to put an element;we add it to the end (tail) of the queue and increment the tail index. A sequence ofput and getoperations causes the queue to appear to move through the array, as illustrated in the figurebelow. When it hits the end of the array, we arrange for it to wrap around to the beginning. Thedetails of this compuation are given in the program given below the shown figure.
F igur e (Q2): A F IFO queue example,
array implementation
This sequence shows the data
manipulation underlying the abstract
representation in the previous figure
when we implement the queue by storing
the items in an array, keeping indices to
the beginning and end of the queue, and
wrapping the indices back to the
beginning of the array when they reach
the end of the array. In this example, the
tail index wraps back to the beginning
when the second T is inserted, and the
head index wraps when the second S is
removed..
FIRS*T*IN
***FI*RS***T*OU
T*****
F
I
RST
I
NFI
R
STOUT
FF IF I RF I R S
I R SI R S T
R S TR S T IR S T I N
S T I NT I N
I NI N FI N F I
N F IN F I RN F I R S
F I R SI R S
R ST R ST ST O ST O U S
T O U T ST O U T
O U TU T
T
The QUEUE ADTAn array implementation of the QUEUE ADT is given herein. The interface part of the QUEUEADT is given below:
template class QUEUE{
private:enum Size {maxN=80};Item q[maxN+1]; int N, head, tail;
public:QUEUE();int empty() const;void put(Item);Item get();
};
The implementation part of the QUEUE ADT is shown below:
#include "queue.h"template QUEUE::QUEUE()
{ N = maxN+1; head = N; tail = 0; }
7/29/2019 Pds Fall2003
24/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 22
template int QUEUE::empty() const
{ return head % N == tail; }template void QUEUE::put(Item item)
{ q[tail++] = item; tail = tail % N; }template
Item QUEUE::get(){ head = head % N; return q[head++]; }
The following example shows a client program that uses the QUEUE ADT. Compare theoutput with that of the similar program that uses the STACK ADT, which is given in theprevious section.
#include #include "queue.cpp"int main(){
QUEUE q1;q1.put(11);q1.put(22);cout
7/29/2019 Pds Fall2003
25/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 23
CHAPTER(4)
POINTERS
4.1 What Is a Pointer?
A PCs random access memory (RAM) is comprised of many thousands of sequential storagelocations. Each storage location is identified by a unique address. The memory addresses in agiven computer range from 0 to a maximum value that depends on the amount of memoryinstalled.
When you declare a variable in C++, the compiler sets aside memory to store that variable.The storage location has a unique address. The compiler associates that address with thevariable name. When your program uses the variable name, it automatically accesses theproper memory location. The location is being used, but it is hidden from you you need not
be concerned with it.
The following figure shows schematically a variable named rate that has been declared andinitialized to 100. The compiler has set aside storage at address 1003 for the variable, and hasassociated the name rate with the address 1003.
1000 1001 1002 1003 1004
100
rate
4.2 Creating a Pointer
You should note that the address of the variable rate (or any other variable) is a number andcan be treated like any other number in C++. If you know a variable's address, you can createa second variable in which to store the address of the first. The first step is to declare avariable to hold the address ofrate. Give it the name prate, for example.
float *prate;
At first, prate is uninitialized. Storage has been allocated forprate but its value isundetermined (suppose it is at address 1001), as shown in the Figure below.
1000 1001 1002 1003 1004
? 100
prate rate
memory storage has been allocated for the variable prate
The next step is to store the address of the variable rate in the variable prate:
prate = &rate;
7/29/2019 Pds Fall2003
26/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 24
Because prate now contains the address ofrate, it indicates the location where rate is storedin memory. In C++ parlance, prate points to rate, or is apointerto rate. This is shown below:
1000 1001 1002 1003 1004
1003 100
prate rate
The variable prate contains the address of the variable rate and is therefore a pointer to rate
To summarize, a pointer is a variable that contains the address of another variable. Now youcan get down to the details of using pointers in your C++ programs.
Hint: You should note that the address of the variable rate is itself a number. A pointer is anumeric value, like all variables, must be declared before it can be used.
To print the content ofrate, we can use the following statement:
cout
7/29/2019 Pds Fall2003
27/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 25
POINTERS CONTAIN MEMORY ADDRESSES, NOT VALUES!
The operator& gives the address of an object.
The operator* is the indirection or dereferencing operator (used to accessthe object the pointer points to)
4.3 Using Pointers
To see more examples of pointers, suppose that x and y are integers and ip is a pointer to int.The sequence below shows how to declare a pointer and how to use & and *:
int x = 1, y = 2, z[10];int *ip; //ip is a pointer to int
ip = &x; //ip now points to xy = *ip; //y is now 1*ip = 0; // x is now 0ip = &z[0]; //ip now points to z[0]
If ip points to the integer x, then *ip can occur in any context where x could, so
*ip = *ip + 10;
increments *ip by 10 (i.e. x is icreased by 10). The statement
y = *ip + 1;
takes whatever the pointer ip points to, adds 1 and assigns the result to y. The statement
*ip += 1;
increments what ip points to, as do
++*ip;
and(*ip)++;
The parentheses are necessary in this last example; without them, the statement wouldincrement ip instead of what it points to.
Since pointers are variables, they can be used without dereferencing. For example, if iq isanother pointer to int,
iq = ip;
copies the contents of ip into iq, thus making iq point to whatever ip pointed to.
A complete program is given below:#include
int main(){int count = 10, x, * ptr_int;
// this assigns the memory address of count to ptr_intptr_int = &count;
//assigns the value stored at the address specified byptr_int to xx = *ptr_int;
cout
7/29/2019 Pds Fall2003
28/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 26
#include
int main(){
char c = 'Q';char *ptr_char = &c;
cout
7/29/2019 Pds Fall2003
29/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 27
// Another program with pointers#include
int main(){
int i1, i2, *p1, *p2;
i1 = 5;
p1 = &i1;i2 = *p1 / 2 + 10;p2 = p1;
cout
7/29/2019 Pds Fall2003
30/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 28
making the if statement from above program
if( date_pointer->month == 08 ).....
Therefore, there are three ways to access a structure member:
Using the structure name
Using a pointer to the structure with the indirection operator (*)
Using a pointer to the structure with the indirect membership operator (->)
If p_str is a pointer to the structure str, the following expressions are all equivalent:str.memb(*p_str).membp_str->memb
Example:
// Program to illustrate structure pointers#include
int main(){
struct date {int month, day, year;
};date today, *date_ptr;
date_ptr = &today;date_ptr->month = 6;date_ptr->day = 4;date_ptr->year = 1987;
cout
7/29/2019 Pds Fall2003
31/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 29
4.5 Pointers and Objects4.5.1 Declaration and Access
Pointers can point to objects as well as to simple data types and arrays, for exampleDistance *dpointer;
Just as we do with structures, we access object members using the (*dpointer).member
form, ordpointer->member form.
Example
// accessing member functions by pointer#include ////////////////////////////////////////////////////////////////class Distance //English Distance class
{private:
int feet;
float inches;public:
void getdist() //get length from user{cout > feet;cout > inches;}
void showdist() //display distance{ cout
7/29/2019 Pds Fall2003
32/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 30
public:void setName() //set the name
{cout > name;}
void printName() //get the name
{cout
7/29/2019 Pds Fall2003
33/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 31
One way to obtain the desired effect is for the calling program to use call by reference (seechapter 1). Another way is to pass pointers to the values to be changed:
swap (&a, &b);
Since the operator & produces the address of a variable, &a is a pointer to a. In swap itself, theparameters are declared to be pointers, and the operands are accessed indirectly through
them. void swap (int *px, int *py) //interchange *px and *py{
int temp;
temp = *px;*px = *py;*py = temp;
}
The above action may be shown pictorially as follows:
Pointer arguments enable a function to access and change objects in the functions that calledit. It should be clear by now why we use the & operator with the scanf() function. Without the &operator scanf() fails to pass the input into the actual parameters.
Example://This programs inputs a time in seconds and converts it to hours,//minutes and seconds.
#include
void time_hms(int t, int *h, int *m, int *s);
int main(){
int time; //original data valueint hours, minutes, seconds; //computed values
couttime;time_hms(time, &hours, &minutes, &seconds);
cout
7/29/2019 Pds Fall2003
34/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 32
void time_hms(int t, int *h, int *m, int *s){
int temp = t/60; //total minutes
*s = t % 60; //number of seconds*m = temp % 60; //number of minutes*h = temp / 60; //number of hours
}
4.7 Pointers and Arrays
In C++ there is a strong relationship between pointers and arrays, strong enough that pointersand arrays should be discussed simultaneously. Any operation that can be achieved by arraysubscripting can be done with pointers. The pointer version will in general be faster.
The declaration
int a[10];
defines an array a of size 10, that is a block of 10 consecutive objects named a[0], a[1], , a[9].
a:a[0] a[1] a[9]
The notation a[i] refers to the i-th element of the array. If pa is a pointer to an integer, declared as
int *pa;
then the assignment
pa = &a[0];
sets pa to point to element zero of a; that is, pa contains the address of a[0].
pa:
a:a[0] a[1] a[9]
Now the assignment
x = *pa;
will copy the contents of a[0] into x.
If pa points to a particular element of the array, then by definition pa+1 points to the nextelement, pa+i points i elements after pa, pa-i points i elements before. Thus, if pa points toa[0],
*(pa+1)
refers to the content of a[1], pa+i is the address of a[i], and *(pa+i) is the content of a[i].
pa: pa+1: pa+2:
a:a[0] a[1] a[9]
7/29/2019 Pds Fall2003
35/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 33
These remarks are true regardless of the type or size of the variables in the array a. Themeaning of "adding 1 to a pointer," and by extension, all pointer arithmetic, is that pa+1 pointsto the next object, and pa+i points to the ith object beyond pa.
BY definition, the value of a variable or expression of type array is the address of element zeroof the array. Thus after the assignment
pa = &a[0];pa and a have identical values. Since the name of an array is a synonym for the location of theinitial element, then the assignment pa=&a[0] can also be written as
pa = a;
A reference to a[i] can be written as *(a+i). In evaluating a[i], C++ converts it to *(a+i)immediately; the two forms are equivalent. Applying the operator & to both parts of thisequivalence, it follows that &a[i] = a+i are also identical: a+i is the address of the ith elementbeyond a. If pa is a pointer, expressions may use it with a subscript; pa[i] is identical to*(pa+i).
An array-and-index expression is equivalent to one written as a pointer and offset.
There is one difference between array name and a pointer that must be kept in mind. A pointeris a variable, so pa=a and pa++ are legal. But an array name is not a variable; constructionslike a=pa and a++ are illegal.
When an array name is passed to a function, what is passed is the location of the initialelement. Within the called function, this argument is a local variable, and so an array nameparameter is a pointer, that is a variable containing an address. We can use this fact to writestrlen, which computes the length of a string.
//strlen returns the length of a string sint strlen (char *s){
int n;
for (n=0; *s!='\0'; s++)n++;
return n;}
Since s is a pointer, incrementing it is perfectly legal; s++ has no effect on the character stringin the function that called strlen(), but merely increments strlen's private copy of the pointer.
A formal parameter in a function definition,char s[];
andchar *s;
are equivalent.
4.8 Pointer Arithmetic
Only two arithmetic operations can be used on pointers: addition and subtraction. To
understand what occurs in pointer arithmetic, let p be a pointer to int with a current value of2000, and assume that integers are 2 bytes long. After the expression
p++;
7/29/2019 Pds Fall2003
36/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 34
the content of p is 2002, not 2001! Each time p is incremented, it points to the next integer.The same is true of decrements. For example,
p--;
will cause p to have the value 1998, assuming that it previously was 2000.
Each time a pointer is incremented it points to the memory location of the next element of itsbase type. Pointers increase or decrease by the length of the data type they point to. Considerthe following declaration (according to Borland C++ specifications):
int *ip;long *lp;float *fp;char *cp;double *dp;
thenip++ will increase ip by 2,
lp++ will increase lp by 4,fp++ will increase fp by 4,cp++ will increase cp by 1,dp++ will increase dp by 8.
You are not limited to increment and decrement, however. You may also add or subtractintegers to or from pointers. The statement
p = p + 9;
makes p point to the ninth element of p type beyond the one it is currently pointing to.
Besides addition and subtraction of a pointer and an integer, the only other operation allowed
is to subtract a pointer from another pointer. This makes sense when handling arrays.
You cannot multiply or divide pointers.You cannot add pointers.You cannot add or subtract type float or double to pointers.
Example://strlen returns the length of a string sint strlen (char *s){
char *p=s;
while (*p != '\0')p++; //pointer is incremented
return p - s; //pointers are subtracted}
It is possible to compare pointers in a relational expression, as the following example shows:Assume that p and q are pointers, the following statement is perfectly valid.
if (p
7/29/2019 Pds Fall2003
37/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 35
(a) pt = table;*pt = 0;*(pt+2) = 3.14;
(b) pt = table + 2;qt = pt;*qt = 2.718;
(c) pt = table;qt = table + 10;
cout
7/29/2019 Pds Fall2003
38/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 36
int main(){
char *s="Dynamic memory allocation";int len = strlen(s); //get length of schar *ptr;
ptr=new char[len+1]; //set aside memory: string+'\0'
strcpy(ptr,s); //copy s to new memory area ptrcout
7/29/2019 Pds Fall2003
39/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 37
CHAPTER(5)
FILE INPUT/OUTPUT
5.1 Disk File I/O with StreamsA stream is a general name given to a flow of data.
Input stream Output stream
In C++ a stream is represented by an object of a particular class. So far we have used the cinand cout stream objects. Different streams are used to represent different kinds of data flow.
Most programs need to save data to disk files and read it back in. Working with disk filesrequires another set of classes:
ifstream forinput, fstream for both input and output, and ofstream foroutput.These classes are declared in the fstream.h file.
5.2 Formatted File I/OIn formatted I/O, numbers are stored on disk as a series of characters. Thus 6.02, rather thanbeing stored as a 4-byte type float or an 8-byte type double, is stored as the characters 6, .,0, and 2. This can be inefficient for numbers with many digits, but its appropriate in manysituations and easy to implement. Characters and strings are stored more or less normally.
5.2.1 Writing data
#include #include
int main(){
char ch='X';int j=77;double d=6.02;char str1[]="data";char str2[]="strucures";
ofstream outfile("fdata.txt");
outfile
7/29/2019 Pds Fall2003
40/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 38
In the above program we declare outfile object and initialize it to the file fdata.txt. Thisinitialization opens the file on the disk. If the file does not exist, it is created. If it does exist, it istruncated and the new data replaces the old.
Note: If the file is in a floppy disk, in a folder called myFolder for example, use the file name as:
a:\\myFolder\\fdata.txt
5.2.2 Reading Data
We can read the file generated by the above program by using an ifstream object, initializedto the name of the file. The file is automatically opened when the object is created. We canthen read from it using the (>>) operator.
#include #include
int main(){
char ch;int j;double d;char str1[10];char str2[10];
ifstream infile("fdata.txt");
infile >> ch >> j >> d >> str1 >> str2;cout
7/29/2019 Pds Fall2003
41/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 39
5.2.3 Character I/O
The put() and get() functions can be used to output and input single characters. Here is aprogram that outputs a string one character at a time.
#include #include #include
int main(){
char str[]="Time is a great teacher, but unfortunately\nit killsall its pupils.";
ofstream outfile("test.txt");
for (int j=0;j
7/29/2019 Pds Fall2003
42/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 40
coutin_name;
coutout_name;
//open input file stream
ifstream infile(in_name);
//open output file streamofstream outfile(out_name);
//Read a character from infile and write it in//outfile, exit loop when eof is reached
while( !infile.eof()){
infile.get(c);outfile.put(c);
}
cout
7/29/2019 Pds Fall2003
43/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 41
//erase bufferfor (j=0;j
7/29/2019 Pds Fall2003
44/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 42
ExampleThe following examples reads data stored in the binary file list.out, which was created by theabove program, into an array called list. It then displays the array content on the screen.
#include #include
int main(){
struct entry {char fname[20];char lname[20];char phone[10];
};entry list[4];int i;
ifstream inf("list.out",ios::binary);inf.read((char*)list,4*sizeof(entry));
//Print two blank lines.cout
7/29/2019 Pds Fall2003
45/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 43
CHAPTER(6)
LINKED LISTS
6.1 IntroductionA linked listis a useful method of data storage that can easily be implemented in C++. There
are several kinds of linked lists, including single-linked lists, double-linked lists, and binarytrees. Each type is suited for certain types of data storage. The one thing that these lists havein common is that the links between data items are defined by information that is contained inthe items themselves, in the form of pointers. This chapter explains the most fundamental kindof linked list: the single-linked list (which is referred to as simply a linked list).
6.2 Creating a Linked List
A linked list is comprised of a series of nodes, each node containing a data element, and apointer to the next node, e.g.,
A pointer that stores the address of the first node is usually called the head of the list. Astructure, which contains a data element and a pointer to the next node, is created by,
struct list {int value;list *next;
};
This defines a new data structure called list(actually the definition of a node), which containstwo members. The first is an integer called value. The second is called next, which is a pointer
to another list structure (or node). Suppose that we declare two structures to be of the sametype as list, e.g.,
list n1, n2;
The nextpointer of structure n1 may be set to point to the n2structure by
n1.next = &n2; // assign address of first element in n2 to the pointer next of the n1 structure
which creates a linkbetween the two structures.
// Program to illustrate linked lists#include int main() {
struct list {int value;list *next;
};list n1, n2, n3, *head=&n1;int i;
n1.value = 100;n2.value = 200;n3.value = 300;n1.next = &n2;n2.next = &n3;n3.next = 0; //NULL, as shown in the figure below
i = n1.next->value;cout
7/29/2019 Pds Fall2003
46/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 44
The following diagram illustrates the linked list created by the above program.
In using linked list structures, it is common to assign the value of 0 to the last pointer in the list,to indicate that there are no more nodes in the list, e.g.,
n3.next = 0;
6.3 Deleting a node from a linked list
To delete a node from the list we simply assign its link field (next field in this example) to thelink field of the previous node (or to the head pointerif it is the first node). If the node wasdynamically created, we use the delete statement to deallocate the memory reserved for it.The following statement deletes n2:
n1.next = n2.next; // deletes n2
The following diagram illustrates deleting n2 from the above linked list. Notice that n2 stilloccupies memory, but it is not part of the linked list. We cannot delete n2 since it was not
created dynamically. The gray arrows show previous links.
6.4 Adding nodes to a linked list (Inserting a node)
Nodes may be added (inserted) to a linked list at the beginning, at the end, or somewhere in themiddle of the list. To add a node, we only need the address of the new node and the node on
the left. This left node could be the linked list head(in the case of insertion at the beginning), thelast node (address=null), or any node in the middle.
Let us add node n1_2 between n1 and n2:
n1_2.next = n1.next; // adds node n1_2n1.next = &n1_2;
To add a node at the beginning of the list (node n0, say), we use the headof the list:n0.next = head; // adds node n0head = &n0;
value=100 next
n1
value=200 next
n2
value=300
n3head
headvalue=300
n3
value=200 next
n2
value=100 next
n1
value=200 next
n2
value=300
n3head
value=100 next
n1
value next
n1_2
value=100 next
n1value=200 next
n2value=300
n3head
value=100 next
n0
7/29/2019 Pds Fall2003
47/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 45
We can also add a node (let us say node n4) to the end of a list, as shown in the followingstatements:
n4.next = 0; //adds node n4 (it is possible to replace 0 with n3.next)n3.next = &n4;
6.5 Traversing a linked list
Traversing a linked list means visiting each node of the list. To achieve this we utilize a pointer,
ptr, which is initialized to the address of the first node (also stored in head). Each time we
visit a node, we access the data element(s) and then set the pointerptr to point to the
following node. This is achieved by
ptr = ptr->next;
where nextis the link field. The following program illustrates this technique.
// Program to illustrate traversing a list#include int main(){
struct list {int value;list *next;
};
list n1, n2, n3, n4, *head=&n1;list *ptr = head;
n1.value = 100;n1.next = &n2;n2.value = 200;
n2.next = &n3;n3.value = 300;n3.next = &n4;n4.value = 400;n4.next = 0;while( ptr != 0 ){
cout
7/29/2019 Pds Fall2003
48/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 46
This program uses a pointer calledptrto cycle through the linked list. Note that we may simplywrite the while loop condition to read as:while(ptr) , since any non-zero value is t rueand 0 isfalse.Practice Exercise:
1. Define a structure called node, which contains an integer element called data, and apointer to a structure of type node called next_node.
2. Declare three structures called node1, node2, node3, of type node.
3. Write C++ statements which will link the three nodes together, with node1 at the head ofthe list, node2 second, and node3 at the tail of the list. Assign the value NULL tonode3.next to signify the end of the list.
4. Using a pointerlist, of type node, which has been initialized to the address ofnode1,write C++ statements which will cycle through the list and print out the value of eachnodes data field.
5. Assuming the state of the list is that as in 3., write C++ statements which will insert anew node node1a between node1 and node2, using the pointerlist(which is currently
pointing to node1). Assume that a pointernew_node points to node node1a.
6.6 Working with Dynamically Created Nodes
Nodes in a linked list are usually created dynamicallyusing the new operator, then added to
the list. Whenever a statement containing the new operator is executed, storage is allocated
from a pool of available memory called the heap. When a node is deleted, its allocated
memory is returned to the heap using the delete operator. If we neglect this, our program
eats up available memory resources, and the system may eventually be out of memory!
Let us create our previous linked list using dynamic memory allocation. The list structure is
struct list {int value;list *next;
};
First we create the list head and initialize it with 0, indicating that the list is empty.
list *head=0; //this is represented as:
Now, let us create a node and add it to the list. We need a pointer to store the address of the
current node of the list; call it listptr.
list * listptr;
listptr = new list; //create a new node and store its address in listptr.This is illustrated in the following diagram:
To add the newly created node to the list we use the information stored in the head pointer as
shown in the following statements. Notice that the new node has no identifier (variable name),but we know its address. Making use of the structure pointer operator (arrow operator; ->) wecan access its members.
listptr ->next = head;head = listptr;
head
listptr
head
value=? next=?
value=?
listptr
head
WARNING:It's important to switch thepointers in the correct order. If you reassign
the head pointer first, you will lose the list!
7/29/2019 Pds Fall2003
49/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 47
To create another node, again we use the new operator, and store the returned address in a
pointernewnode, say.
newnode = new list;
The following statements add this node to the linked list and set listptrto point to the end node.
newnode->next = listptr->next;listptr->next = newnode;
listptr = newnode; //set listptr to point to the end node
To continue adding nodes we keep repeating the above sequence of statements.
Let us assume that the value field is to be read from the standard input. We need to resetlistptr and then traverse the list. The value field of the node we access is read from thekeyboard. This is illustrated in the following statements:
listptr = head; //reset listptrwhile(listptr){
coutlistptr->value;listptr = listptr->next;
}
Practice exercise:
1. Write a function called delete_node, which accepts a pointer to a list, and a pointer tothe node to be deleted from the list, e.g.
void delete_node(node *head, node *delnode );
2. Write a function called insert_node, which accepts a pointer to a list, a pointer to a newnode to be inserted, and a pointer to the node after which the insertion takes place, eg
void insert_node(node *head, node *newnode, node *prevnode);
newnode
value=?value=?
listptr
head
listptr
value=?value=? next
head
7/29/2019 Pds Fall2003
50/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 48
6.7 A Linked list example
// linked list example#include #include
// definition of a node
struct node {char data[20];
node *next;
};
void freenodes(node * );int insert(node * );void del_node(node *, node * );void list(node * );void menu(node *, node * );
int main()
{node *headptr, *nodeptr;headptr = new node;nodeptr = headptr;headptr->next = NULL;menu( headptr, nodeptr );freenodes( headptr );return 0;
}
// free memory allocated for nodevoid freenodes(node *headptr )
{node *temp;while( headptr ) {
temp = headptr->next;delete headptr;headptr = temp;
}}
// insert a new node after nodeptr, return 1 = successint insert(node *nodeptr ){
char buffer[20];node *newptr;
newptr = new node; // allocate a new nodeif( newptr == NULL ) {
return 0;}else { // fill in its data and add to the list
newptr->next = nodeptr->next;nodeptr->next = newptr;cout>buffer;
strcpy( newptr->data, buffer );}return 1;
}
7/29/2019 Pds Fall2003
51/52
Prog. & Data Structures(702233)/Fall2003/Dr. Sayed A. Hussein 49
// delete a node from listvoid del_node( node *headptr, node *nodeptr ){
node *deletepointer, *previouspointer;char buffer[20];
deletepointer = headptr->next;previouspointer = headptr;// find the entrycout>buffer;while( deletepointer ) {
if( strcmp( buffer, deletepointer->data ) == 0 ) {// delete node pointed to by delete pointerpreviouspointer->next = deletepointer->next;break;
}
else {// goto next node in listdeletepointer = deletepointer->next;previouspointer = previouspointer->next;
}}
// did we find it?if( deletepointer == NULL )
cout
7/29/2019 Pds Fall2003
52/52
// main menu systemvoid menu( node *headp, node *nodep ){
int menuchoice = 1;
while( menuchoice != 4 ) {cout