Professional Documents
Culture Documents
اعـــــــــــداد وتجميـــــع:
Lab.3: Stacks…...……………………………………………………………………………………. 16
Lab.7: Doubly Linked Lists & stack and Queue using Linked List………………………………… 49
❖ Objectives:
- Revision about functions in C++
- To be able to deal with 1-D and 2-D arrays (input to and print them)
- To be able to pass 1-D and 2-D arrays to functions.
❖ Examples:
1- Write a program to input an integer array of size of 50 with n elements and do the following:
a- Search about the even numbers in the array
b- Sort the array in ascending order.
➢ The C++ Code:
#include<iostream>
#include<stdio.h>
#include<conio.h>
using namespace std;
/* Function decleration */
void search(int [],int); // Function to saerch about the even numbers
void sort(int [],int); // Function to sort the array
void printing(int [],int); // Function to print the array elements
const int Max_Size=100;
main()
{
int A[Max_Size],n,i;
cout<<" Enter the No. of elements:";
cin>>n;
cout<<" Enter the elemetns to the array:"<<endl;
for (i=0; i<n; i++)
cin>>A[i];
cout<<" The Entered array is:"<<'\n';
printing(A,n);
cout<<"the even numbers are in locations: ";
search(A,n);
cout<<endl<<"the array after sorting in ascending order is :"<<endl;
sort(A,n);
printing(A,n);
}
/* Functions definition */
void search(int A[],int n){
for(int i=0;i<n;i++)
1
ماجد البعداني/.م lab.1: Arrays (1-D and 2-D) -عملي-هياكل بيانات وخوارزميات
if(A[i]%2==0)
cout<<i<<" ";
}
void sort(int A[],int n)
{
int temp,i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(A[j]<A[i])
{
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
void printing (int A[],int n)
{
for (int i=0; i<n; i++)
cout<<"A["<<i<<"]="<<A[i]<<endl;
}
2- Write a C++ program to define an integer matrix of size 100×100 with n×m elements then find the
largest element in each row and in each column in the matrix.
➢ The C++ Code:
#include<iostream>
#include<stdio.h>
#include<conio.h>
using namespace std;
const int max_row=50;
const int max_col=50;
/* Function decleration */
void printing(int [][max_col],int,int); // Function to print the matrix
void larg_row(int [][max_col],int,int); // Function to find the largest
element in each row
void larg_col(int [][max_col],int,int); // Function to find the largest
element in each row
2
ماجد البعداني/.م lab.1: Arrays (1-D and 2-D) -عملي-هياكل بيانات وخوارزميات
main()
{
int A[max_row][max_col],i,j,n,m;
cout<<"enter the number of rows: ";
cin>>n;
cout<<"enter the number of columns: ";
cin>>m;
cout<<"enter the elements of the matrix :"<<endl;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
cin>>A[i][j];
cout<<"the matrix is: \n";
printing(A,n,m);
cout<<" the largest element in each row are: "<<endl;
larg_row(A,n,m);
cout<<endl<<" the largest element in each column are: "<<endl;
larg_col(A,n,m);
}
/* Functions definition */
void printing(int A[][max_col],int n,int m)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
cout<<A[i][j]<<" ";
cout<<endl;
}
}
void larg_row(int A[][max_col],int n,int m)
{
int i,j,max;
for( i=0;i<n;i++)
{
max=A[i][0];
for (j=1;j<m;j++)
if(A[i][j]>max)
max=A[i][j];
3
ماجد البعداني/.م lab.1: Arrays (1-D and 2-D) -عملي-هياكل بيانات وخوارزميات
cout<<"the max of row "<<i+1<<"="<<max<<endl;
}
}
void larg_col(int A[][max_col],int n,int m)
{
int i,j,max;
for( i=0;i<m;i++)
{
max=A[0][i];
for (j=1;j<n;j++)
if(A[j][i]>max)
max=A[j][i];
cout<<"the max of col "<<i+1<<"="<<max<<endl;
}
}
Home Work 1:
✓ Write a program to input an integer array of size of 100 with n elements and calculate the
summation of the prime numbers in it?
✓ Write a C++ program to define an integer matrix of size 50×50 with n×m elements then find
the summation of the elements in each row.
قم باستخدام الدوال إلجابه السؤالين السابقين:✓ مالحظة
4
ماجد البعداني/.م lab.2: Review about Pointers and Structures -عملي-هياكل بيانات وخوارزميات
The computer memory is a sequential collection of storage cells as shown in Figure (1). Each cell commonly
known as a byte, has a number called address associated with it. Typically, the addresses are numbered
consecutively, starting from zero. The last address depends on the memory size. A computer system having 64 k
memory will have its last address as 65,535.
Address
Memory Cell
65,535
int quantity=159;
the system will allocate location for this variable and puts the value 159 in that location. Assuming that the
address location is 5000, we can represent this as shown in Figure (2).
quantity variable
159 value
5000 address
We can access to value 159 either by the name quantity or the address 5000. Since the memory addresses
are simply numbers, they can be assigned to some variables called pointer variables.
5
ماجد البعداني/.م lab.2: Review about Pointers and Structures -عملي-هياكل بيانات وخوارزميات
Variable value address
p 5000 5084
We can return the address of a variable with the help of the operator & available in C++.
P=& quantity;
P will contain the address of the variable quantity in the memory (i.e. 5000).
Ex:
main( ) {
int x=10;
char a='A';
cout<<x<<" is stored at location "<<&x;
cout<<a<<"is stored at location "<<&a;
}
❖ Declaring of Initializing Pointer Variables:
Syntax:
data_type *pointer_name;
EX:
int x;
int *p;
p=&x;
6
ماجد البعداني/.م lab.2: Review about Pointers and Structures -عملي-هياكل بيانات وخوارزميات
cout<<"value of n : "<<n<<'\n';
cout<<"value of x before : " <<x;
*p= 100; \\ the value of x will change to 100
cout<<" value of x after : "<< x;
}
The * operator can be remembered as " value at address".
#include<iostream>
#include<conio.h>
int i;
if (x[i]>*p)
if (x[i]<*s)
}}
main( ){
7
ماجد البعداني/.م lab.2: Review about Pointers and Structures -عملي-هياكل بيانات وخوارزميات
cout<<"Enter the number of elements n= ";
cin>>n;
cin>>Array[i];
/* initializing the MAX and MIN values with the first element in the array */
MAX=Array[1];
MIN=Array[1];
getch( );
8
ماجد البعداني/.م lab.2: Review about Pointers and Structures -عملي-هياكل بيانات وخوارزميات
main( ){
int Array[MAX_Size], MAX, MIN, n;
cout<<"Enter the number of elements n= ";
cin>>n;
cout<<"Enter the elements of the array"<<'\n';
for (int i=1;i<=n; i++)
cin>>Array[i];
/* initializing the MAX and MIN values with the first element in the array */
MAX=Array[1];
MIN=Array[1];
/* calling the function of MAX_MIN*/
MAX_MIN (Array, MAX, MIN, n);
cout<<" the max value is :" <<MAX<<endl;
cout<<" the min value is :" <<MIN<<endl;
getch();
}
Structures
Consider a book database consisting of book name, author, number of pages and price. We can define a
structure to hold this information as follow:
struct book
{
char title[20];
char author[15];
int pages;
float price;
};
• Declaring Structure Variables:
A structure variable declaration is similar to the declaration of any other data type. It includes the following
elements:
1- The structure tag name.
2- List of variable names separated by commas.
3- A terminating semicolon.
9
ماجد البعداني/.م lab.2: Review about Pointers and Structures -عملي-هياكل بيانات وخوارزميات
EX:
book book1,book2,book3;
• Accessing the Structure Members:
There are two ways to access the members of a structure variable:
1- Using the Dot '.' Notation:
Example:
struct Employee
{
char name[20];
char department[30];
float salary;
};
main( ) {
Employee Person1,Person2;
cout<<"Enter the values of the first structure variable"<<'\n';
cin>>Person1.name>>Person1.department>>Person1.salary;
cout<<"Enter the values of the second structure variable"<<'\n';
cin>>Person2.name>>Person2.department>>Person2.salary;
cout<<"the stored valuse"<<endl;
cout<< Person1.name<<'\t'<<Person1.department<<'\t'<<Person1.salary;
cout<< Person2.name<<'\t'<<Person2.department<<'\t'<<Person2.salary;
getch();
}
10
ماجد البعداني/.م lab.2: Review about Pointers and Structures -عملي-هياكل بيانات وخوارزميات
char name[20];
char department[30];
float salary;
};
main( ) {
Employee Person1, *ptr;
ptr=&Person1;
cout<<"Enter the values of the second structure variable"<<'\n';
cin>>(*ptr). name>> (*ptr). department>>(*ptr). salary;
cout<<"the values of the structure variable are"<<'\n';
cout<<ptr-> Name<<'\t'<< ptr-> Department<< '\t'<< ptr-> salary;
getch( );
}
Example
❖ write a C++ program to define a structure Class of three members: name, an array of three subjects and grade
then do the following:
1- Create tow structure variables student1 and student2.
2- Create a function to input the name and marks of subjects for the two students.
3- Create a function to input the grade as follow:
A if average of of the marks >=90
B if 80=<average<90
C if 65=<average<80
F if average<65
4-Create a function to print the values of members for the two students
❖ The program:
/* 1- by using pointer */
#include<iostream>
using namespace std;
struct Class{
11
ماجد البعداني/.م lab.2: Review about Pointers and Structures -عملي-هياكل بيانات وخوارزميات
string name;
int sub[5];
char grade;
};
void input_name_sub(Class *);
void input_grade(Class *);
void print(Class );
main(){
Class student1,student2;
cout<<"enter name and marks of subjects for the first student:"<<endl;
input_name_sub(&student1);
cout<<"enter name and marks of subjects for the second student:"<<endl;
input_name_sub(&student2);
/* assigning the grade for the students using input grade function */
input_grade(&student1);
input_grade(&student2);
cout<<endl<<"-------------output----------------"<<endl;
cout<<"first student:"<<endl;
print(student1);
cout<<"second student:"<<endl;
print(student2);
}
void input_name_sub(Class *p){
cout<<"name:";
cin>>p->name;
cout<<"marks:";
for(int i=0;i<5;i++)
cin>>p->sub[i];
}
void input_grade(Class *p){
int sum=0;
double avg;
for (int i=0;i<5;i++)
sum=sum+p->sub[i];
avg=sum/5;
if (avg>=90)
p->grade='A';
12
ماجد البعداني/.م lab.2: Review about Pointers and Structures -عملي-هياكل بيانات وخوارزميات
else if (avg>=80 )
p->grade='B';
else if (avg>=65)
p->grade='C';
else
p->grade='F';
}
void print(Class student){
cout<<"name:"<<student.name<<'\n';
cout<<"marks:" ;
for (int i=0;i<5;i++)
cout<<student.sub[i]<<" ";
cout<<endl<<"grade:"<<student.grade<<'\n'; }
/* 2- by using reference */
#include<iostream>
using namespace std;
struct Class{
string name;
int sub[5];
char grade;
};
void input_name_sub(Class &);
void input_grade(Class &);
void print(Class );
main(){
Class student1,student2;
cout<<"enter name and marks of subjects for the first student:"<<endl;
input_name_sub(student1);
cout<<"enter name and marks of subjects for the second student:"<<endl;
input_name_sub(student2);
/* assigning the grade for the students using input grade function */
input_grade(student1);
input_grade(student2);
cout<<endl<<"-------------output----------------"<<endl;
cout<<"first student:"<<endl;
print(student1);
cout<<"second student:"<<endl;
13
ماجد البعداني/.م lab.2: Review about Pointers and Structures -عملي-هياكل بيانات وخوارزميات
print(student2);
}
void input_name_sub(Class &p){
cout<<"name:";
cin>>p.name;
cout<<"marks:";
for(int i=0;i<5;i++)
cin>>p.sub[i];
}
void input_grade(Class &p){
int sum=0;
double avg;
for (int i=0;i<5;i++)
sum=sum+p.sub[i];
avg=sum/5;
if (avg>=90)
p.grade='A';
else if (avg>=80 )
p.grade='B';
else if (avg>=65)
p.grade='C';
else
p.grade='F';
}
void print(Class student){
cout<<"name:"<<student.name<<'\n';
cout<<"marks:" ;
for (int i=0;i<5;i++)
cout<<student.sub[i]<<" ";
cout<<endl<<"grade:"<<student.grade<<'\n';
}
14
م /.ماجد البعداني lab.2: Review about Pointers and Structures هياكل بيانات وخوارزميات-عملي-
15
م /.ماجد البعداني lab.3: stacks هياكل بيانات وخوارزميات-عملي-
❖ ما هو ال STACK؟
-نوع من أنواع هياكل البيانات حيث يتم فيه تخزين البيانات بترتيب معاكس لترتيب استعادتها (سحبها) ،أي أن آخر قيمة يتم إدخالها
(دفعها) إلى ال Stackهي أول قيمة يتم سحبها من المكدس ،وتدعى هذه االلية .)last in first out( LIFO
-الحذف واإلضافة تتم من طرف واحد فقط يدعى .)Top Of Stack( TOS
-ينفذ ال STACKمجموعة من العمليات األساسية وهي:
Push -دفع البيانات إلى المكدس.
Popسحب البيانات من المكدس. -
IsFull -التحقق من ان المكدس ممتلئ.
IsEmpty -التحقق من ان المكدس فارغ.
-يمكن بناء ال Stackباستخدام:
-1المصفوفات (ِ.)Arrays based implementation
-2القوائم المترابطة (.)Linked Lists based implementation
Array-based implementation
❖ اإلضافة ): PUSH(x
)3-Push(10
TOS = 3
• مالحظة :نتوقف عنما يصبح ال STACKممتلئ (بمعنى عندما تكون قيمه ال TOSتساوي الحجم األقصى (.))MaxSize
16
م /.ماجد البعداني lab.3: stacks هياكل بيانات وخوارزميات-عملي-
• مالحظة :نتوقف عنما يصبح ال STACKفارغ (بمعنى عندما تكون قيمه ال TOSتساوي صفر).
17
ماجد البعداني/.م lab.3: stacks -عملي-هياكل بيانات وخوارزميات
18
ماجد البعداني/.م lab.3: stacks -عملي-هياكل بيانات وخوارزميات
main()
{
stackType stack;
int n;
cout<<"enter the maxsize of the stack: ";
cin>>n;
initializeStack(stack,n);
push(stack,20);print(stack);
push(stack,15);print(stack);
push(stack,500);print(stack);
push(stack,-20);print(stack);
int x;
x=pop(stack);
cout<<"the poped element is: "<<x<<endl;
print(stack);
x=pop(stack);
cout<<"the poped element is: "<<x<<endl;
print(stack);
x=pop(stack);
cout<<"the poped element is: "<<x<<endl;
print(stack);
x=pop(stack);
}
#include<iostream>
#include<string>
using namespace std;
struct stackType
{
int MaxStackSize;
int TOS;
19
ماجد البعداني/.م lab.3: stacks -عملي-هياكل بيانات وخوارزميات
char *list;
};
20
ماجد البعداني/.م lab.3: stacks -عملي-هياكل بيانات وخوارزميات
main()
{
stackType stack;
initializeStack(stack,30);
string original,reversed="";
21
م /.ماجد البعداني lab.4: Queues هياكل بيانات وخوارزميات-عملي-
❖ ما هو ال Queue؟
-نوع من أنواع هياكل البيانات حيث يتم فيه تخزين البيانات بحيث يتم استعادتها حسب ترتيب ورودها فالقيمة التي تُخزن اوالَ تتم
استعادتها أوال .وتدعى هذه االلية .)First in first out( FIFO
-الحذف واإلضافة تتم من طرفين مختلفين حيث تتم عمليه اإلضافة عن طريق طرف يسمى ( )Rearوالحذف عن طريق طرف يسمى
(.)Front
-ينفذ ال Queueمجموعة من العمليات األساسية وهي:
Enqueue -اضافه بيانات الى ال .Queue
Dequeueسحب بيانات من ال .Queue -
IsFull -التحقق من ان الطابور ممتلئ.
IsEmpty -التحقق من ان الطابور فارغ.
-يمكن بناء ال Queueباستخدام:
-1المصفوفات (ِ.)Arrays based implementation
-2القوائم المترابطة (.)Linked Lists based implementation
هناك نوعين من الطوابير: -
-1الطابور الخطي ()Linear Queue
-2الطابور الدائري ()Circular Queue
Array-based implementation
لنفرض ان لدينا Queueبحجم اقصى ( )maxsizeوليكن 4كما هو موضح بالشكل التالي:
-يكون ال Queueفي حالته االبتدائية عندما يكون rear=-1و( front=0حسب افتراضنا نحن)
rear=-1 Front=0
]int Q[4
rear=0 rear=1
Front=0 Front=0
)1- Enqueue(8 )2- Enqueue(10
8 8 10
0 1 2 3 0 1 2 3
22
م /.ماجد البعداني lab.4: Queues هياكل بيانات وخوارزميات-عملي-
rear=0
Front=0
)3- Enqueue(-5
8 10 -5
0 1 2 3
✓ مالحظة :يكون الطابور ممتلئ في حالة كان rear=mazsize-1
-وتكون الخطوات الالزمة لحذف عنصر من الطابور )(( x=dequeueحيث ان xهي القيمة المحذوفة من الطابور) هي :
-1اخذ العنصر من الطابور عن طريق ال :front
]X=Q[front
-2زيادة ال frontبمقدار واحد
Front++
سنقوم االن بحذف عنصرين من الطابور كما هو مبين في االشكال التالية:
rear=2 rear=2
Front=1 Front=2
4- x= Dequeue()=8 5- x= Dequeue()=10
10 -5 -5
0 1 2 3 0 1 2 3
23
م /.ماجد البعداني lab.4: Queues هياكل بيانات وخوارزميات-عملي-
Count=0
24
ماجد البعداني/.م lab.4: Queues -عملي-هياكل بيانات وخوارزميات
int Front;
int Rear;
int *list;
};
void initializeQueue(queueType &curr,int max)
{
curr.Front=0;
curr.Rear=-1;
curr.count=0;
curr.maxQueueSize=max;
curr.list=new int[max];
}
bool isEmpty(queueType &curr)
{
return (curr.count==0);
}
bool isFull(queueType &curr)
{
return (curr.count==curr.maxQueueSize);
}
void addQueue(queueType &curr,int x)
{
if(isFull(curr)==false)
{
curr.Rear=(curr.Rear+1)%curr.maxQueueSize;
curr.count++;
curr.list[curr.Rear]=x;
}
else
cout<<"Full Queue";
}
int deleteQueue(queueType &curr)
{
if(!isEmpty(curr))
{
25
ماجد البعداني/.م lab.4: Queues -عملي-هياكل بيانات وخوارزميات
int x=curr.list[curr.Front];
curr.Front=(curr.Front+1)%curr.maxQueueSize;
curr.count--;
return x;
}
else
{
cout<<"empty Queue";
return 0;
}
}
void print(queueType curr)
{
cout<<"queue elements: ";
while(!isEmpty(curr))
{
cout<<deleteQueue(curr)<<" ";
}
cout<<endl;
}
main( ){
queueType queue;
initializeQueue(queue,10);
int x,n;
cout<<"enter the number of element to add into queue: ";
cin>>n;
for(int i=0;i<n;i++){
cin>>x;
addQueue(queue,x);}
print(queue);
cout<<"the deleted element: "<<deleteQueue(queue)<<endl;
print(queue);
cout<<"the deleted element: "<<deleteQueue(queue)<<endl;
print(queue);
}
26
م /.ماجد البعداني lab.4: Queues هياكل بيانات وخوارزميات-عملي-
27
ماجد البعداني/.م lab.4: Queues -عملي-هياكل بيانات وخوارزميات
current.list=new int[maxSize];
}
bool isEmpty(stackType current)
{
return (current.TOS==0);
}
bool isFull(stackType current) {
return(current.TOS==current.MaxStackSize);
}
28
ماجد البعداني/.م lab.4: Queues -عملي-هياكل بيانات وخوارزميات
while(!isEmpty(stack))
cout<<pop(stack);
}
main()
{
int num;
cout<<"Enter the decimal number: "<<endl;
cin>>num;
cout<<"the equivalent binary number is :" <<endl;
Decimal_To_Binary(num);
}
29
م /.ماجد البعداني )lab.5: Linked Lists(I هياكل بيانات وخوارزميات-عملي-
-1عبارة عن مجموعة من العناصر(السجالت) تُدعي العُقد( .)nodesيتم تخزين هذه العناصر في الذاكرة بشكل غير متجاور
(هذا عكس المصفوفات حيث يتم تخزين البيانات في الذاكرة بشكل متتالي (متجاور)).
-2كل عقدة ( )nodeتتكون على األقل من حقلين .حقل البيانات لتخزين البيانات ( )dataوحقل العنوان ()address
لتخزين عنوان العقدة التالية.
-3عنوان العقدة األولى في القائمة المترابطة يُخزن دائما ً في متغير منفصل (هذا المتغير من نوع مؤشر) يسمى ب head
-الن كل عقدة في القائمة المترابطة تحتوي على حقلين ،نحتاج تعريف كل عقدة كسجل ( )structureكما يلي:
{struct Node
;int data حقل البيانات //
; Node *link حقل العنوان(مؤشر للعقدة التالية) //
;}
;Node *head مؤشر ألول عقدة في القائمة //
-اعتمادا على الشكل السابق ،الجدول التالي يوضح قيم ال headوبعض العقد الموجودة في القائمة المترابطة:
توضيح القيمة
200 head
300 head->link
30
م /.ماجد البعداني )lab.5: Linked Lists(I هياكل بيانات وخوارزميات-عملي-
130
Temp 130
data link
Temp 130
100
data link
ت -اسناد العنوان الموجود في ال headلحقل العنوان ( )linkفي العقدة الجديدة.
;Temp -> link= head
ث -نجعل ال headيشير للعقدة الجديدة وذلك بإسناد قيمة ال Tempالى ال head
;head= Temp
31
م /.ماجد البعداني )lab.5: Linked Lists(I هياكل بيانات وخوارزميات-عملي-
Temp 250
data link
ب -ادخال القيمة ( xولتكن مثال )50لحقل البيانات ( )dataفي العقدة الجديدة وقيمة NULLلحقل العنوان (ألنها ستكون
اخر عقدة):
;Temp ->data= x
;Temp -> Link= NULL
250
نقوم بإسناد قيمة ال ( Tempعنوان العقدة الجديدة) لحقل العنوان الخاص باخر عقدة في القائمة وبالتالي تصبح العقدة
األخيرة مشيرة للعقدة الجديدة وبالتالي تُصبح العقدة الجديدة هي األخيرة في القائمة.
; Node *Temp2=head
{)while (Temp2 -> link != NULL
} ;Temp2= Temp2 -> link
Temp2 -> link= Temp
ث -إذا كانت القائمة فارغه ( ،)head=NULLنقوم بإسناد عنوان العقدة الجديدة ( )Tempالى headبشكل مباشر.
;head=Temp
32
م /.ماجد البعداني )lab.5: Linked Lists(I هياكل بيانات وخوارزميات-عملي-
400
Temp 400 55
data link
ب -التحرك بحلقة تكرارية حتى الوصول للعقدة التي تسبق المكان المراد إضافة العقدة الجديدة فيه (حسب افتراضنا نريد
الوصول للعقدة ،)1ثم نقوم بعمل الخطوتين التاليتين:
-اسناد العنوان الموجود في العقدة التي وصلنا اليها (هنا )1لحقل العنوان الموجود في العقدة الجديدة.
-اسناد عنوان العقدة الجديدة ( )Tempلحقل العنوان للعقدة التي وصلنا اليها.
ت -إذا كان المكان المراد إضافة العقدة اليه هو 1فإننا نقوم باستدعاء داله اإلضافة في البداية.
33
ماجد البعداني/.م lab.5: Linked Lists(I) -عملي-هياكل بيانات وخوارزميات
Temp ->data= x;
if (pos==1)
inserting _beginning (x);
else {
struct Node *Temp2=head;
for (i=1;i<pos-1;i++)
Temp2=Temp2 -> link;
Temp -> link=Temp2 ->link;
Temp2 -> link =Temp;
}
400
55 200
data link
34
ماجد البعداني/.م lab.5: Linked Lists(I) -عملي-هياكل بيانات وخوارزميات
int data;
Node *link ;
};
Node *head;
void inserting_beginning (int x){
Node *Temp= new Node(); /* creation of new node */
Temp->data= x;
Temp->link=head;
head=Temp;
}
void print ( )
{
Node *Temp=head;
cout<<" The list is: " ;
while (Temp!=NULL) {
cout<<Temp->data<<" " ;
Temp= Temp->link;
}
cout<<endl ;
}
void Inserting_End(int x) {
Node *Temp= new Node ();
Temp->data= x;
Temp->link= NULL;
if(head==NULL)
head=Temp;
else
{
Node *Temp2=head ;
while (Temp2 -> link != NULL){
Temp2= Temp2->link;
}
Temp2->link=Temp;
}
}
35
ماجد البعداني/.م lab.5: Linked Lists(I) -عملي-هياكل بيانات وخوارزميات
36
ماجد البعداني/.م lab.5: Linked Lists(I) -عملي-هياكل بيانات وخوارزميات
cin>>x;
int pos;
cout<<" enter the position :";
cin>>pos;
Inserting_Position(x,pos);
}
if (ch==4){
print();
}
}while (ch != 0);
getch();
}
37
م /.ماجد البعداني )lab.6: Linked Lists (II هياكل بيانات وخوارزميات-عملي-
;delete Temp
يُصبح شكل القائمة بعد حذف العقدة األولى كالتالي:
int { ) ( Deleting_begining
)if (head==NULL
;"cout<<"Empty List
else
{
;Node *Temp=head
;int x=Temp -> data
;head = Temp->link
}};return x
38
م /.ماجد البعداني )lab.6: Linked Lists (II هياكل بيانات وخوارزميات-عملي-
Temp Temp2
ث -اسناد عنوان العقدة التالية للعقدة ال ُمراد حذفها لحقل العنوان الخاص بالعقدة السابقة للعقدة المراد حذفها
;Temp->link=Temp2->link
130 200 300 500
130 0100 200 45 500 -90 500 30 NULL
0
Temp Temp2
ج -حذف العقدة فعليا ً من الذاكرة فيصبح شكل القائمة بعد الحذف كما يلي:
;delete Temp2
39
ماجد البعداني/.م lab.6: Linked Lists (II) -عملي-هياكل بيانات وخوارزميات
Node *Temp2;
for (int i=1;i<pos-1;i++){
Temp= Temp -> link;
}
Temp2=Temp->link;
int x=Temp2->data;
Temp -> link =Temp2->link;
return x;
}}
✓ سوف نختبر دوال الحذف المكتوبة باألعلى بعد ان نقوم ببناء قائمة مترابطة ولبناء القائمة نحتاج أحد دوال اإلضافة مع حلقة
:)تكرارية (هنا سوف استخدم دالة اإلضافة في البداية مع حلقة تكراريه لبناء القائمة
#include<iostream>
#include<conio.h>
using namespace std;
struct Node{
int data;
Node *link ;
};
Node *head;
void inserting_beginning (int x){
struct Node *Temp= new Node( );
Temp->data= x;
Temp->link=head;
head=Temp;
}
int Deleting_begining ( ) {
if (head==NULL)
cout<<"Empty List";
else
{
Node *Temp=head;
int x=Temp -> data;
head = Temp->link;
return x;
}}
40
ماجد البعداني/.م lab.6: Linked Lists (II) -عملي-هياكل بيانات وخوارزميات
41
م /.ماجد البعداني )lab.6: Linked Lists (II هياكل بيانات وخوارزميات-عملي-
;cin>>x
} ;)inserting_beginning (x
;cout<<"the list before deleting any item is: "<<endl
;) (print
;cout<<"__________________________________________________"<<endl
;cout<<"the list after deleting at beginning"<<endl
;) ( int y=Deleting_begining
;cout<<" deleted element= "<<y<<endl
;)( print
;cout<<"the list after deleting the third Node"<<endl
;)y= Deleting_position (3
;cout<<" deleted element= "<<y<< endl
;)( print
;)(getch
}
42
ماجد البعداني/.م lab.6: Linked Lists (II) -عملي-هياكل بيانات وخوارزميات
43
ماجد البعداني/.م lab.6: Linked Lists (II) -عملي-هياكل بيانات وخوارزميات
cout<<Node_num<<" ";
count++;
}
Temp=Temp->link;
Node_num++;
}
if (count==0)
cout<<"the element is not found";
cout<<endl;
}
void initialize()
{
Node *Temp=head;
while(head!=NULL)
{
Temp=head;
head=head->link;
delete Temp;
}
}
main( ){
head=NULL ;
int n,x;
cout<<"enter the number of elements n= ";
cin>>n;
cout<<" enter the elements "<<endl;
for (int i=1;i<=n; i++){
cout<<"enter element: ";
cin>>x;
inserting_beginning (x);
}
print();
cout<<"enter the element to search about:";
cin>>x;
search(x);
44
م /.ماجد البعداني )lab.6: Linked Lists (II هياكل بيانات وخوارزميات-عملي-
;cout<<"the list after deleting all nodes is: "<<endl
;)(initialize
}
❖ تمرين :2قم ببناء قائمتين مترابطتين وادخل اليهما العناصر التالية (سوف استخدم داله اإلضافة في النهاية)
األولى80 -20 100 50 60 70 :
الثانية500 600 700 800 900 :
ثم قم بكتابة دالة لدمج القائمتين المترابطتين (القائمة األولى ثم الثانية).
• مالحظات هامة قبل قراءة البرنامج:
-1كل قائمة مترابطة كما عرفنا سابقا ً بتكون معرفه برأسها (المتغير الذي يحتوي على عنوان اول عقدة في القائمة) ،وبما اننا نحتاج
قائمتين فسوف نُعرف رأس للقائمة األولى (هنا اسميناه )firstورأس للقائمة الثانية (هنا اسميناه .)second
-2في البرامج السابقة كنا نعرف رأس القائمة كمتغير عام ( )global variableوبالتالي نستطيع الدخول الية من أي مكان في البرنامج،
لكن هنا قمنا بتعريف رأسي القائمتين كمتغيرين محليين ( )local variableفي دالة mainوبالتالي سوف نكون بحاجة إلرسال قيمها
للدوال واستقبالها ومن ثم ارجاعها اما عن طريق returnاو عن طريق استخدام المؤشرات.
>#include<iostream
>#include<conio.h
;using namespace std
{struct Node
;int data
; Node *link
;}
)void print ( Node *head
45
ماجد البعداني/.م lab.6: Linked Lists (II) -عملي-هياكل بيانات وخوارزميات
{
Node *Temp=head;
cout<<" The list is: " ;
while (Temp!=NULL) {
cout<<Temp->data<<" " ;
Temp= Temp->link;
}
cout<<endl ;
}
Node * Inserting_End(Node *head,int x) {
Node *Temp= new Node ();
Temp->data= x;
Temp->link= NULL;
if(head==NULL)
head=Temp;
else
{
Node *Temp2=head ;
while (Temp2 -> link != NULL){
Temp2= Temp2->link; }
Temp2->link=Temp;
}
return head;
}
// ) وتعمل على دمج القائمة الثانية للقائمة األولىfirst, second( هذه الدالة تستقبل رأسي القائمتين
void merge(Node **first,Node **second)
{
//إذا كانت القائمة األولى فارغة
if (*first==NULL)
*first=*second;
else
{
46
ماجد البعداني/.م lab.6: Linked Lists (II) -عملي-هياكل بيانات وخوارزميات
Node *Temp=*first;
while (Temp->link!=NULL)
Temp=Temp->link;
Temp->link=*second;
}
}
main (){
Node *first=NULL;
Node *second=NULL;
int x,n;
cout<<"enter the number of elements for the first linked list: ";
cin>>n;
cout<<" enter the elements "<<endl;
for (int i=1;i<=n; i++){
cout<<"enter element: ";
cin>>x;
first=Inserting_End (first,x);
}
cout<<"enter the number of elements for the second linked list: ";
cin>>n;
cout<<" enter the elements "<<endl;
for (int i=1;i<=n; i++){
cout<<"enter element: ";
cin>>x;
second=Inserting_End (second,x);
}
cout<<"___________________________________________"<<endl;
cout<<" the two lists befor merging are : "<<endl;
print(first);
print(second);
cout<<"___________________________________________"<<endl;
cout<<" the tow lists after merging is: "<<endl;
47
ماجد البعداني/.م lab.6: Linked Lists (II) -عملي-هياكل بيانات وخوارزميات
merge(&first,&second);
print(first);
}
48
م /.ماجد البعداني lab.7: Doubly Linked Lists & stack and Queue using Linked List هياكل بيانات وخوارزميات-عملي-
❖ القائمة المترابطة الثنائية هي عبارة عن قائمة مترابطة كل عقدة فيها تحتوي على ثالثة حقول ،حقل للبيانات وحقل يحتوي عنوان
العقدة التالية وحقل يحتوي عنوان العقدة السابقة كما هو مبين بالشكل التالي ،ال firstهنا يحتوي عنوان اول عقدة وال last
ُمشير آلخر عقدة.
49
ماجد البعداني/.م lab.7: Doubly Linked Lists & stack and Queue using Linked List -عملي-هياكل بيانات وخوارزميات
50
ماجد البعداني/.م lab.7: Doubly Linked Lists & stack and Queue using Linked List -عملي-هياكل بيانات وخوارزميات
51
ماجد البعداني/.م lab.7: Doubly Linked Lists & stack and Queue using Linked List -عملي-هياكل بيانات وخوارزميات
while(t!=NULL)
{
/* if node to be deleted is found */
if (t->data==x)
{
/* if node to be deleted is the first node */
if (t==f)
{
f=f->next;
f->prev=NULL;
}
else
{
/* if node to be deleted is the last node */
if (t->next==NULL)
{
t->prev->next=NULL;
l=t->prev;
}
else
{
/* if node to be deleted is any intermediate node */
t->prev->next=t->next;
t->next->prev=t->prev;
}
}
delete t;
return ; /* return back after deletion */
}
t=t->next;
}
}
void main()
{
52
ماجد البعداني/.م lab.7: Doubly Linked Lists & stack and Queue using Linked List -عملي-هياكل بيانات وخوارزميات
جبميع عملياته باستخدام القوائم املرتابطة بدال من استخدام املصفوفاتstack تصميم ال
53
م /.ماجد البعداني lab.7: Doubly Linked Lists & stack and Queue using Linked List هياكل بيانات وخوارزميات-عملي-
الشكل التالي يوضح خطوات عملية اإلضافة (بفرض ان القيمة ال ُمراد اضافتها هي ')'D
الشكل التالي يوضح خطوات عملية حذف عنصر من المكدس (التي يُشير اليها ال )stackTop
54
ماجد البعداني/.م lab.7: Doubly Linked Lists & stack and Queue using Linked List -عملي-هياكل بيانات وخوارزميات
:• البرنامج التالي لتصميم المكدس بجميع عملياته باستخدام القوائم المترابطة
#include<iostream>
using namespace std;
struct node
{
int data;
node *link;
};
struct stackType
{
node *Tos;
};
void initializeStack (stackType &curr)
{
node *t;
while(curr.Tos!=NULL)
{
t=curr.Tos;
curr.Tos=curr.Tos->link;
delete t;
}
}
bool isEmpty(stackType current)
{
return (current.Tos==NULL);
}
bool isFull(stackType current)
{
return false;
}
void push(stackType ¤t,int element)
{
node *t=new node;
t->data=element;
55
ماجد البعداني/.م lab.7: Doubly Linked Lists & stack and Queue using Linked List -عملي-هياكل بيانات وخوارزميات
t->link=current.Tos;
current.Tos=t;
}
int pop(stackType ¤t)
{
if(!isEmpty(current))
{
node *t=current.Tos;
current.Tos=current.Tos->link;
int x=t->data;
delete t;
return x;
}
else
{
cout<<"the stack is empty";
return 0;
}
}
void print(stackType curr)
{
while(!isEmpty(curr))
{
cout<<curr.Tos->data<<" ";
curr.Tos=curr.Tos->link;
}
cout<<"\n";
}
main()
{
stackType stack;
stack.Tos=NULL;
push(stack,48);print(stack);
push(stack,15);print(stack);
push(stack,500);print(stack);
56
ماجد البعداني/.م lab.7: Doubly Linked Lists & stack and Queue using Linked List -عملي-هياكل بيانات وخوارزميات
push(stack,-20);print(stack);
int x;
x=pop(stack);
cout<<"the poped element is: "<<x<<endl;
print(stack);
x=pop(stack);
cout<<"the poped element is: "<<x<<endl;
print(stack);
x=pop(stack);
cout<<"the poped element is: "<<x<<endl;
print(stack);
x=pop(stack);
}
جبميع عملياته باستخدام القوائم املرتابطة بدال من استخدام املصفوفاتQueue تصميم ال
:)• البرنامج التالي لتصميم المكدس بجميع عملياته باستخدام القوائم المترابطة (قم بتحليله بنفسك
#include<iostream>
using namespace std;
struct node
{
int data;
node *link;
};
struct queueType{
node *Front;
node *Rear;
};
void initializeQueue(queueType &curr,int max)
{
node *t;
while(curr.front!=NULL)
{
t=curr.front;
57
ماجد البعداني/.م lab.7: Doubly Linked Lists & stack and Queue using Linked List -عملي-هياكل بيانات وخوارزميات
curr.front=curr.front->link;
delete t;
}
curr.rear=NULL;
}
bool isEmpty(queueType &curr)
{
return (curr.front==NULL);
}
bool isFull(queueType &curr)
{
return false;
}
void addQueue(queueType &curr,int x)
{
node *temp=new node;
temp->data=x;
temp->link=NULL;
if (curr.rear==NULL) //if initially the queue is empty
{
curr.front=temp;
curr.rear=temp;
}
else
{ //add newNode at the end
curr.rear->link=temp;
curr.rear=curr.rear->link;
}
}
int deleteQueue(queueType &curr)
{
if(!isEmpty(curr))
{
node *temp=curr.front;
curr.front=curr.front->link;
58
ماجد البعداني/.م lab.7: Doubly Linked Lists & stack and Queue using Linked List -عملي-هياكل بيانات وخوارزميات
int x=temp->data;
delete temp;
if(curr.front==NULL) //if after deletion the queue is empty
curr.rear = NULL; //set rear to NULL
return x;
}
else
{
cout<<"empty Queue";
return 0;
}
}
void print(queueType curr)
{
cout<<"queue elements: ";
while(!isEmpty(curr))
{
cout<<curr.front->data<<" ";
curr.front=curr.front->link;
}
}
cout<<endl;
}
void main( ){
queueType queue;
queue.front=NULL;
queue.rear=NULL;
int x,n;
cout<<"enter the number of element to add into queue: ";
cin>>n;
for(int i=0;i<n;i++){
cin>>x;
addQueue(queue,x);}
print(queue);
cout<<"the deleted element: "<<deleteQueue(queue)<<endl;
59
ماجد البعداني/.م lab.7: Doubly Linked Lists & stack and Queue using Linked List -عملي-هياكل بيانات وخوارزميات
print(queue);
cout<<"the deleted element: "<<deleteQueue(queue)<<endl;
print(queue);}
60
م /.ماجد البعداني )lab.8: Trees (I هياكل بيانات وخوارزميات-عملي-
❖ مفهوم الشجرة:
هي مجموعة منتهية مكونه من عقدة او أكثر بحيث تحقق ما يلي:
.1يوجد عقدة مصممة بشكل خاص تدعى جذر الشجرة()root
.2العقد المتبقية تُجزأ الى ( )n≥0من المجموعات المنفصلة T1, T2, T3,….. , Tnحيث كل مجموعة من هذه المجموعات
تشكل شجرة .تُدعى هذه المجموعات اشجارا ً فرعية ( )sub-treesمن عقدة الجذر كما هو موضح بالشكل التالي:
❖ تعاريف هامة:
61
م /.ماجد البعداني )lab.8: Trees (I هياكل بيانات وخوارزميات-عملي-
} .height (T) =max {height (x): x is a node in Tمثل ارتفاع الشجرة الموجودة في األعلى يساوي 3
-5عمق عقدة )depth(x)( xهو عدد االتصاالت ( )edgesفي أطول مسار من هذه العقدة الى عقدة ورقية (.)leaf node
مثلً Depth(B)=2, Depth(C)=1
1
62
م /.ماجد البعداني )lab.8: Trees (I هياكل بيانات وخوارزميات-عملي-
وبالتالي يُصبح شكل الشجرة الثنائية في الشكل 1الموجود في الصفحة السابقة كالتالي:
63
م /.ماجد البعداني )lab.8: Trees (I هياكل بيانات وخوارزميات-عملي-
في حالة استخدمنا طريق Inorderسوف تُطبع العناصر بالترتيب التالي: •
D G B E A C H F
في حالة استخدمنا طريق Preorderسوف تُطبع العناصر بالترتيب التالي: •
A B D G E C F H
في حالة استخدمنا طريق Postorderسوف تُطبع العناصر بالترتيب التالي: •
G D E B H F C A
64
م /.ماجد البعداني )lab.8: Trees (I هياكل بيانات وخوارزميات-عملي-
عبارة عن شجرة ثنائية لكن بشرط ان قيم كل العقد الموجودة على يمين عقدة ما أكبر من قيمة العقدة نفسها وقيم كل العقد الموجودة
على يسارها اقل من قيمة العقدة نفسها .هذا الترتيب سوف يجعل عملية البحث أكثر سرعة وكفاءة.
الشكل :2شجرة ثنائيه لكنها ليست شجرة بحث ثنائية الشكل :1شجرة ثنائيه لكنها ليست شجرة بحث ثنائية
❖ العمليات األساسية الممكن تطبيقها على شجرة البحث الثنائية:
-1اضافه عنصر جديدة الى الشجرة
-2حذف عنصر من الشجرة
-3التنقل عبر شجرة البحث الثنائية.
-4البحث عن عنصر معين في للشجرة
-5حساب أكبر واقل قيمة في الشجرة
-6حساب طول ( )heightشجرة البحث الثنائية.
9 19
65
ماجد البعداني/.م lab.8: Trees (I) -عملي-هياكل بيانات وخوارزميات
66
م /.ماجد البعداني lab.8: Trees (II): Follow Binary Search Tree هياكل بيانات وخوارزميات-عملي-
لنفرض أننا نرغب بالبحث عن عنصر ب keyيساوي xفي شجرة بحث ثنائية .نبدأ أوال بالجذر .إذا كان الجذر يساوي ،NULL
أي شجرة البحث ال تضمن أي عنصر ،وبالتالي البحث ينتهي بفشل .وإال ،نقارن Xمع keyالجذر ،فإذا كانا متساويين ،عندئذ البحث
ينتهي بنجاح .أما إذا كان xأصغر من keyالجذر فعندئذ يتم البحث في الشجرة الفرعية اليسارية للجذر ،ألنه ال يوجد عنصر في
الشجرة الفرعية اليمينية له keyيساوي .وإذا كان xأكبر من keyالجذر عندئذ يتم البحث في الشجرة الفرعية اليمينية للجذر.
يبدأ بالذهاب إلى االبن اليساري لعقدة الجذر ،ومن ثم إلى ابنه اليساري ،وهكذا حتى يتم الوصول إلى عقدة ال تتضمن ابنا
يسارية .عندئذ تكون هذه العقدة تملك أصغر keyفي الشجرة - .الدالة اإلجرائية المسؤولة عن ذلك:
يأخذ هذا البحث المسار المعاكس حيث تتكرر العملية نفسها ولكن على االبن اليميني للعقدة ،ويستمر حتى يتم العثور على عقدة ال
تتضمن ابنا يمينيا عندئذ تكون هذه العقدة تملك أكبر keyفي الشجرة.
67
م /.ماجد البعداني lab.8: Trees (II): Follow Binary Search Tree هياكل بيانات وخوارزميات-عملي-
مالحظة :قم بإدخال العناصر level by levelمثال عندما تقوم ببناء الشجرة السابقة تقوم بترتيب العناصر وادخالها كالتالي (من
اليسار لليمين):
20 15 25 12 17 22 26 10 13 23 30
>#include<iostream
>#include<stdio.h
;using namespace std
struct binaryTreeNode
{
;int data
;binaryTreeNode *left
;binaryTreeNode *right
;}
)binaryTreeNode * getnewnode(int element
68
ماجد البعداني/.م lab.8: Trees (II): Follow Binary Search Tree -عملي-هياكل بيانات وخوارزميات
{
binaryTreeNode *temp=new binaryTreeNode;
temp->data=element;
temp->left=temp->right=NULL;
return temp;
}
binaryTreeNode * insertBST(binaryTreeNode *root,int element)
{
binaryTreeNode *current;
binaryTreeNode *tempcurrent;
binaryTreeNode *newnode=getnewnode(element);
if (root==NULL)
{
root=newnode;
}
else
{
current=root;
while(current!=NULL)
{
tempcurrent=current;
if (current->data==element)
{
cout<<"duplicated value is not allowed";
}
else if(current->data>element)
current=current->left;
else
current=current->right;
}
if (tempcurrent->data>element)
tempcurrent->left=newnode;
69
ماجد البعداني/.م lab.8: Trees (II): Follow Binary Search Tree -عملي-هياكل بيانات وخوارزميات
else
tempcurrent->right=newnode;
}
return root;
}
void inorder(binaryTreeNode *p)
{
if (p != NULL)
{
inorder(p->left);
cout << p->data << " ";
inorder(p->right);
}}
void preorder(binaryTreeNode *p)
{
if (p != NULL)
{
cout << p->data << " ";
preorder(p->left);
preorder(p->right);
}
}
void postorder(binaryTreeNode *p)
{
if (p != NULL)
{
postorder(p->left);
postorder(p->right);
cout << p->data << " ";
}
}
binaryTreeNode *search(binaryTreeNode *root, int x)
70
ماجد البعداني/.م lab.8: Trees (II): Follow Binary Search Tree -عملي-هياكل بيانات وخوارزميات
{
/* return a pointer to the node that contains x. If there is no such node, return null */
while (root !=NULL) {
if (x == root->data) return root;
if (x < root ->data)
root = root->left;
else
root = root->right;
}
return NULL;
}
int minimum(binaryTreeNode *root)
{
binaryTreeNode *ptr;
while(root !=NULL){
ptr = root;
root= root ->left;
}
return ptr->data;
}
int maximum (binaryTreeNode *root)
{
binaryTreeNode *ptr;
while(root !=NULL){
ptr = root;
root= root ->right;
}
return ptr->data;
}
main ()
{
binaryTreeNode *root=NULL; // empty BST
71
ماجد البعداني/.م lab.8: Trees (II): Follow Binary Search Tree -عملي-هياكل بيانات وخوارزميات
int x,n;
cout<<"enter the no. of nodes you need to add: ";
cin>>n;
cout<<"enter the elements:"<<endl;
for(int i=0;i<n;i++)
{
cin>>x;
root=insertBST(root,x);
}
cout<<"the preorder traversing: "<<endl;
preorder(root);
cout<<endl<<"the postorder traversing: "<<endl;
postorder(root);
cout<<endl<<"the inorder traversing: "<<endl;
inorder(root);
cout<<endl<<"the max element in the tree is : "<<maximum(root)<<endl;
cout<<"the min element in the tree is : "<<minimum(root)<<endl;
cout<<"enter the element to search:";
cin>>x;
binaryTreeNode * ptr;
ptr=search(root,x);
if (ptr==NULL)
cout<<"not found";
else
cout<<"the location of " <<ptr->data<<"is:"<<ptr;
}
72
Data Structures & Algorithms
Lab. 10:Graphs.
Adjacency Matrix for Directed Graph Adjacency Matrix for Undirected Graph
Adjacency List for Directed Graph Adjacency List for Undirected Graph
73
Suppose we have the following weighted directed graph:
6
0 1
7
5 4
2 10
3
4
6
3
4 5
1
74
//print the adjMatrix
int main()
{
int adjMatrix[N][N];
init(adjMatrix);
addEdge(adjMatrix,0,1,6);
addEdge(adjMatrix, 1,2,7);
addEdge(adjMatrix,2, 0, 5);
addEdge(adjMatrix,2, 1, 4);
addEdge(adjMatrix,3, 2, 10);
addEdge(adjMatrix,3,5,6);
addEdge(adjMatrix,4, 5, 1);
addEdge(adjMatrix,5, 4, 3);
printAdjMatrix(adjMatrix);
return 0;
}
75
struct Graph {
// An array of pointers to Node to represent adjacency list
Node* head[N];
};
// data structure to store graph edges
struct Edge {
int src, dest, weight;
};
return graph;
}
76
// Function to print adjacency list representation of graph
void printGraph( Graph* graph)
{
int i;
for (i = 0; i < N; i++)
{
// print current vertex and all ts neighbors
Node* ptr = graph->head[i];
while (ptr != NULL)
{
cout<<i<<" -> "<<ptr->dest<<"("<<ptr->weight<<")"<<"\t";
ptr = ptr->next;
}
cout<<"\n";
}
}
77
Breadth First Search implementation in C++:
0 1
6
3 7
2 3
10 4
20
5
4 5
#include<iostream>
using namespace std;
const int N=6;
//initialize matrix to 0
void init(int arr[ ][N])
{
int i,j;
for(i = 0; i < N; i++)
for(j = 0; j < N; j++)
arr[i][j] = 0;
}
//Add edge. set arr[src][dest] = weight
void addEdge(int arr[][N],int src, int dest,int weight)
{
arr[src][dest] = weight;
arr[dest][src] = weight;
}
void printAdjMatrix(int arr[][N])
{
int i, j;
cout<<"The adjacency matrix for the graph:"<<endl<<endl;
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
}
struct queueType{
int maxQueueSize;
int count;
int Front;
78
int Rear;
int *list; };
void initializeQueue(queueType &curr,int max)
{
curr.Front=0;
curr.Rear=-1;
curr.count=0;
curr.maxQueueSize=max;
curr.list=new int[max];
}
bool isEmpty(queueType &curr)
{
return (curr.count==0);
}
bool isFull(queueType &curr)
{
return (curr.count==curr.maxQueueSize);
}
void addQueue(queueType &curr,int x)
{
if(isFull(curr)==false)
{
curr.Rear=(curr.Rear+1)%curr.maxQueueSize;
curr.count++;
curr.list[curr.Rear]=x;
}
else
cout<<"Full Queue";
}
void deleteQueue(queueType &curr)
{
if(!isEmpty(curr))
{
curr.Front=(curr.Front+1)%curr.maxQueueSize;
curr.count--;
}
else
cout<<"empty Queue";
}
int front(queueType &curr)
{
if(!isEmpty(curr))
return curr.list[curr.Front];
else
cout<<"Empty Queue";
79
}
void print(queueType curr)
{
cout<<"queue elements: ";
while(!isEmpty(curr))
{
cout<<front(curr)<<" ";
deleteQueue(curr);
}
cout<<endl;
}
void BFSGraph(int adjMatrix[][N],int start)
{
queueType Q;
initializeQueue(Q,20);
int visited[N]={0};
visited[start]=1;
addQueue(Q,start);
while (!isEmpty(Q))
{
print(Q);
int current=front(Q);
deleteQueue(Q);
cout<<"visited "<<current<<endl;
for(int i=0;i<N;i++)
{
if(adjMatrix[current][i]!=0 && visited[i]==0)
{
visited[i]=1;
addQueue(Q,i);
}
} }
}
main()
{
int adjMatrix[N][N];
init(adjMatrix);
addEdge(adjMatrix,0,1,6);
addEdge(adjMatrix, 1,2,7);
addEdge(adjMatrix,2, 0, 5);
addEdge(adjMatrix,2, 1, 4);
addEdge(adjMatrix,3, 2, 10);
addEdge(adjMatrix,4, 5, 1);
addEdge(adjMatrix,5, 4, 3);
addEdge(adjMatrix,5,3,6);
80
printAdjMatrix(adjMatrix);
cout<<"enter the start node"<<"\n";
int n; cin>>n;
BFSGraph(adjMatrix,n); }
81