Professional Documents
Culture Documents
Practical No.1
_______________________________________________________________________ _ I!" Getting acquainted with recursion.
#$JECTI%E
The goal of this lab is to help you become acquainted with the use of recursion. Recursion is an ability of a function to call itself. In c it is possible for the function to call themselves. A function is called recursive if a statement with in the body of a function calls the same function.
E& !P'ES" Re cu r s io n :s u m ()
Re cursion: sum()
Department of CSE and IT, JUIT Waknaghat E(ample" factorial) # # *+ , * - . - / - 0 - 1 $otice that *+ , * - .+ .+ , . - /+ ... %an compute factorials recursively &olve base case '1+ , 1+ , 1( then plug in 0+ , 0 - 1+ , 0 - 1 , 02 /+ , / - 0+ , / - 0 , 32
# #
Re cursion
4-Program for calc5lating the factorial of a n5m6er 67 5)ing rec5r)i8e f5nction-4 )include*stdio.h+ )include*conio.h+ int rec 'int(, void main'( int a. fact, printf'/enter any no0(, scanf'/1d0.2a(, fact3rec'a(, printf'/1d0. fact(, 4 rec9int (: ; 5 Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat int f2 if9(,,1: ret5rn91:2 el)e f,(-rec9(<1:2 ret5rn9f:2 = >ec5r)ion %). Iteration" Repetition # Iteration6 e7plicit loop # Recursion6 repeated function calls Termination # Iteration6 loop condition fails # Recursion6 base case recogni8ed 9alance # %hoice between performance 'iteration( and good software engineering 'recursion( #
STUDENT T S?S"
1. Write a recursive function to obtain the first 25 numbers of a Fibonacci series. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence: 1 2 3 5 8 13 21 . 2. Write a recursive function to obtain the running sum of first 25 natural numbers. 3. ! "ositive integer is entered through the #e$board% write a recursive function to obtain the "rime factors of that integer. &. Write a "rogram to calculate result of following with recursive calls of a function. '(2)&)*)8..n '(1+1,)2+2,)3+3,) n+n,. 5. ! five digit "ositive integer is entered through the #e$board% write a recursive function to calculate the sum of digits of 5 digit number. *. Write a recursive function to find out the -./ of numbers. 0. Write a recursive function to generate table of a number.
Practical No.0
_______________________________________________________________________ _ I!" Getting acquainted with recursion with pointer.
#$JECTI%E
The goal of this lab is to help you become acquainted with the use of recursion with pointers. Recursion is an ability of a function to call itself. In c it is possible for the function to call themselves. A function is called recursive if a statement with in the body of a function calls the same function.
STUDENT T S?S"
1. Write a recursive function to find out the reverse of a string using "ointers. 1g. $ashwant o+"% tnawhsa$ 2. Write a recursive function to determine whether a string is "alindrome2 .a"itali3ation and s"acing are ignored. 4est $our with the following two "alindromes and at least one case that is not a "alindrome. 5adam2 I6m !dam !ble was I ere I saw 1lba 3. Write a recursive function that convert a string of numerals to an integer. For e7am"le2 8&35*09 will be converted to &35*0. &. Write a recursive function that changes an integer to a binar$ number. 5. Write a recursive function that removes all the occurrences of a s"ecified character in a string.
Practical No./
_______________________________________________________________________ _
I!" Revision of arrays. strings. pointers. recursion and dynamic memory allocation. #$JECTI%E
The goal of this lab is to help you become acquainted with the use of arrays. strings. pointers. recursion and dynamic memory allocation.
STUDENT T S?S"
1. ! m 7 n matri7 is said to have a saddle "oint if some entr$ a:i;:<; is the smallest value in row i and the largest value in column <. Write a . "rogram that determines a saddle "oint if one e7ists. 2. ! square matri7 ! of si3e m 7 n is said to be s$mmetric if element a i< ( a<i2 for all values of I and <. Write a function sa$2 int is=$mmetric>int a:;:;2 int n? that returns value 1 if the in"ut matri7 is s$mmetric else return value @. 3. Write a function that removes leading s"aces from a given string. &. Write a function that concatenates first n characters of a string to another string. 5. Write a recursive function to find out whether a string is "alindrome or not.
Practical No..
_______________________________________________________________________ _ I!" Getting acquainted with =in>ed list ' =inear =in>ed =ist(.
#$JECTI%E
The goal of this lab is to help you become acquainted with how to create lin>ed list. insert elements into lin>ed list. traverse the lin>ed list. delete elements from the lin>ed list.
'i)t"
=ist is homogeneous collection of elements. with linear relationship between the elements. the list can be ordered or unordered. ? Implementing li)t =ist can be implemented using !. =inear array ". =in>ed list ?
Department of CSE and IT, JUIT Waknaghat Iach structure contains an element of the list and a pointer to structure containing its successor. ? =in>ed implementation allow traverse and search operations to be carried out in linear time. ? Insertion and deletion operations can be implemented efficiently as it requires only rearrangement of pointers. 'inked li)t defined A lin>ed list is a linear collection of data elements. called nodes. the linear order is given by pointers. Iach node is divided into two or more parts. =in>ed list can be of following types6 ? =inear lin>ed list or one way list ? Eoubly lin>ed list or two way list ? %ircular lin>ed list ? Jeader lin>ed list ?
"ext pointer field of 2nd node Information field of second node head is #sed to hold the address of first element of the list. $ast element of the linked list have "%$$ val#e in the next pointer field to mark the end of the list
>epre)entation of 'inear linked li)t &uppose we want to store the list of integer numbers. then the linear lin>ed list can be represented in memory with the following declarations. t7pedef )tr5ct nodet7pe ; int info2 )tr5ct nodet7pe -ne(t2 =node2 node -head2 The above declaration define a new data type. whose each element is of type nodetype and gives it a name node. #peration on 'inear linked li)t) ? %reating an empty list ? Traversing a list ? &earching an element ? Inserting an element ? Eeleting an element Creating an empt7 li)t K Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat In the previous declaration. the variable head is declared as pointer to node data type. ? Lariable head is not yet given a value. ? This variable is used to point to the first element of the list ? &ince the list will be empty in the beginning. the variable head is assigned a sentinel value to indicate the list is empty. void createemptylist'node DDhead( Dhead3$M==, 4 Tra8er)ing a li)t =inear list can be traversed in two ways ? In order traversal ? Reverse order traversal In order tra8er)al" To traverse the linear lin>ed list. we move along the pointer. and process each element till we reach the last element. void traverseinorder'node Dhead( while'headN3$M==( printf'/1dOn0.headP+info(, head3headP+ne7t, 4 4 ? >e8er)e order tra8er)al" To traverse the linear lin>ed list in reverse order. we move along the pointer till we reach the last element. The last element is processed first. then the second last and so on and finally the first element of the list To implement this we use either sac> '=IQF( or recursion. Loid traversereverseorder'node Dhead( if'headP+ne7tN3$M==( traversereverseorder'headP+ne7t(, printf'/1dOn0.headP+info(, 4 4 Searching an element ? In linear lin>ed list. only linear searching is possible. ? This is one of the limitation of the lin>ed list as there is no way to find the location of the middle element of the list =ist can be !. &orted ". Mnsorted 'i)t i) 5n)orted" Ce traverse the list from the beginning. and compare each element of the list with the given element say item to be searched. node Dsearchunsortedlist'node Dhead. int item( R Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat while''headN3$M==( 22'headP+infoN3item(( head3headP+ne7t, return head, 4 'i)t i) )orted" If the list is sorted say in ascending order then we traverse the list from beginning and compare each element of list with item to be searched. If the match occurs. the location of the element is returned. If we reach the element that is greater than item or end of the list $M== value is returned. node Dsearchinsortedlist'node Dhead. int item( while'headN3$M==( if'headP+info33item( return head, else if 'item*headP+info( return $M==, else head3headP+ne7t, 4 return $M==, 4 In)erting an element To insert an element in the list. the first tas> is to get a free node. assign the element to be inserted to the info field of the node. and then new node is placed at the appropriate position by adGusting the appropriate pointer. The insertion in the list can ta>e place at the following positions6 ? At the beginning of the list ? At the end of the list ? After a given element In)ert at the 6eginning of the li)t" Qirst test whether the lin>ed list is initially empty. if yes. then the element is inserted as the first and only one element by performing the following steps6 ? Assign $M== value to the ne7t pointer field of the new node ? Assign address of new node to head If the list is not empty. then the element is inserted as the first element of the list by performing the following steps6 ? Assign value of head variable to the ne7t pointer field of the new node. ? Assign address of the new node to the head. In)ert at the 6eginning of the li)t" Loid insertatbegining'node DDhead.int item( node Dptr, ptr3'nodeD(malloc'si8eof'node((, ptrP+info3item, if'Dhead33$M==( ptrP+ne7t3$M==, else ptrP+ne7t3Dhead, Dhead3ptr, !A Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat 4 In)erting at the end of the li)t" Qirst test whether the lin>ed list is initially empty. if yes. then the element is inserted as the first and only one element by performing the following steps6 ? Assign $M== value to the ne7t pointer field of the new node ? Assign address of new node to head If the list is not empty. then the list is traversed to reach the last element. and then element is inserted as the last element of the list by performing the following steps6 ? Assign $M== value to the ne7t pointer field of the new node ? Assign address of the new node to the ne7t pointer field of the last node. Loid insertatend'node DDhead. int item( node Dptr. Dloc, ptr3'nodeD(malloc'si8eof'node((, ptrP+info3item, ptrP+ne7t3$M==, if'Dhead33$M==( Dhead3ptr, else loc3Dhead, while 'locP+ne7tN3$M==( loc3locP+ne7t, locP+ne7t3ptr, 4 4 In)erting after gi8en element" To insert the new element after the given element. first we find the location. say loc. of the given element in the list. and then the element is inserted in the list by performing following steps6 Assign the ne7t pointer field of the node pointed by loc to the ne7t pointer field of the new node. ? Assign address of the new node to the ne7t pointer field of the node pointed by loc. Loid insertafterelement'node Dhead. int item.int after( node Dptr. Dloc, loc3search'head.after(, if'loc33'nodeD($M==( SDelement after not foundDS return, ptr3'nodeD(malloc'si8eof'node((, ptrP+info3item, ptrP+ne7t3locP+ne7t, locP+ne7t3ptr, 4 Deleting an element ? To delete an element from the list. first the pointer are set properly and then the memory occupied by the node to be deleted is deallocated'free(. ? The deletion in the list can ta>e place at the following positions. !! Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi ?
Department of CSE and IT, JUIT Waknaghat !. At the beginning of the list ". At the end of the list 5. After a given element Deleting from the 6eginning of the li)t An element from the beginning of the lists can be deleted by performing following steps6 ? Assign the value of head ' address of the first element of the list( to a temporary variable 'say ptr( ? Assign the value of the ne7t pointer field of the first node to head. ? Eeallocate the memory occupied by the node pointed to by ptr. Deleting from the 6eginning of the li)t Loid deletefrombegining' node DDhead( node Dptr, if'Dhead33$M==( return, else ptr3Dhead, Dhead3'Dhead(P+ne7t, free'ptr(, 4 4 Deleting from the end of the li)t To delete from the end of the list. we first traverse to the second last element of the list. Then the last element can be deleted by performing following steps6 ? Assign the ne7t pointer field of the second last node to a temporary variable ' say ptr(. ? Assign value $M== to the ne7t pointer field of the second last node of the list. ? Eeallocate the memory occupied by the node pointed to by ptr. Deleting from the end of the li)t Loid deletefromend' node DDhead( node Dptr.Dloc, if 'Dhead33$M==( return, else if ''Dhead(P+ne7t33'nodeD( $M==( ptr3Dhead, Dhead3$M==, free'ptr(, 4 else loc3Dhead, ptr3'Dhead(P+ne7t, while'ptrP+ne7tN3$M==( loc3ptr, ptr3ptrP+ne7t, 4 locP+ne7t3$M==, !" Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat free'ptr(, 4 4 Deleting after a gi8en element To delete an element after a given element. first we find the location say 'loc( of the element after which the element can be deleted by performing the following steps6 ? Assign ne7t pointer field of the node pointed by the loc to temporary variable 'say ptr(. ? Assign the ne7t pointer field of the node to be deleted to the node pointed to by loc ? Eeallocate the memory occupied by the node pointed to by ptr. Deleting after a gi8en element Loid deleteafterelement' nodeDhead. int after( node Dptr. Dloc, loc3search'head.after(, if'loc33'nodeD($M==( SDelement after not foundDS return, ptr3locP+ne7t, locP+ne7t3ptrP+ne7t, free'ptr(, 4 Deleting Entire li)t 9efore the program terminates. the entire list must be deletedso that the memory occupied by the nodes of the list can be used for other purposes. This tas> can be accomplished by performing the following steps6 ? Assign the head pointer to a temporary variable. say ptr. ? Advance the head pointer to the ne7t node. ? Eeallocate the memory occupied by the node pointed to by ptr. The above steps are repeated till the entire list is deleted. Deleting Entire li)t Loid deletelist'node DDhead( node Dptr, while'DheadN3$M==( ptr3Dhead, Dhead3'Dhead(P+ne7t, free'ptr(, 4 4
STUDENT T S?S"
1. W!A to im"lement the Binear lin#ed list. Aerform the following o"erations on the lin#ed list: !ddition of numbers after a "articular location. /eletion of the number given b$ the user. .ounting the no of nodes. /is"la$ing the lin#ed list. !5 Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat !dding the numbers at the beginning of the lin#ed list. !""ending the numbers given b$ the users.
Practical No.*
_______________________________________________________________________ _ I!" Getting acquainted with =in>ed list ' =inear =in>ed =ist(.
#$JECTI%E
The goal of this lab is to help you become acquainted with how to create lin>ed list. insert elements into lin>ed list. traverse the lin>ed list. delete elements from the lin>ed list.
STUDENT T S?S"
1. 4wo lin#ed lists are given as !: 12 22 32 &2 52 * C: 02 82 D2 1@2 112 12 5a#e a third lin#ed list so that it is in the following order. .: 12022282 ..2*212 2. W!A for "rinting the common elements in two given lin#ed lists. 3. W!A that traverse a list im"lemented using lin#ed list and delete all nodes whose #e$s are negative. &. ! lin#ed list contains some "ositive numbers and some negative numbers. Ese this lin#ed list to W!A for creating two more lin#ed list2 one containing all "ositive no and other all negative nos.
Practical No.3
_______________________________________________________________________ _ I!" Getting acquainted with =in>ed list 'Eoubly =in>ed =ist(.
#$JECTI%E
The goal of this lab is to help you become acquainted with how to create doubly lin>ed list. insert elements into lin>ed list. traverse the lin>ed list. delete elements from the lin>ed list. Do56l7 'inked 'i)t In doubly lin>ed list. also called the two way list. each node is divided into three parts6 ? The first part called. previous pointer field. contains the address of preceding element in the list. ? The second part contains the information of the list. ? The third part. called ne7t pointer field. contains the address of the succeeding element in the list. In addition. two pointer variables. e.g. head and tail. are used that contains the address of first element and the address of last element of the list.
tail
"ext pointer field of 2nd node Information field of second node &revio#s pointer field of 2nd node
>epre)entation of do56l7 linked li)t ? &uppose we want to store list of integer. t7pedef )tr5ct nodet7pe ; )tr5ct nodet7pe -pre82 int info2 !; Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat )tr5ct nodet7pe -ne(t2 =node2 node -head,-tail2 The above declaration defines a new data type. whose each element is of type nodetype and gives it name node. #peration on Do56l7 linked li)t) ? %reating an empty list ? Traversing a list ? &earching an element ? Inserting an element ? Eeleting an element Creating an Empt7 li)t ? In the previous declaration. the variable head and tail are declared as pointer to a node data type. ? These Lariables are not yet given a value. ? The head is used to point to the first element of the list and tail is used to point to the last element of the list. ? &ince the list will be empty in the beginning. the variable head and tail are assigned a sentinel value to indicate the list is empty. void createemptylist'node DDhead. node DDtail( Dhead3Dtail3$M==, 4 Tra8er)ing a li)t Eoubly lin>ed list can be traversed in both way and that too very conveniently. ? In order traversal ? Reverse order traversal In order tra8er)al" To traverse the doubly lin>ed list. we move along the pointer. and process each element till we reach the last element. void traverseinorder'node Dhead( while'headN3$M==( printf'/1dOn0.headP+info(, head3headP+ne7t, 4 4 >e8er)e order tra8er)al" The following listing shows the various steps required for traversing a doubly lin>ed list in the bac>ward direction. Loid traversereverseorder'node Dtail( if'tailN3$M==( printf'/1dOn0.tailP+info(, tail3tailP+prev, 4 4 !< Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat Searching an element The doubly lin>ed list can be traversed in any order to reach the given element. The following listing shows the various steps required for searching an element from the beginning. node Dsearch 'node Dhead. int item( while'headN3$M==( if'headP+info33item( return head, head3headP+ne7t, 4 return $M==, 4 In)erting an element To insert an element in the list. the first tas> is to get a free node. assign the element to be inserted to the info field of the node. and then new node is placed at the appropriate position by adGusting the appropriate pointer. The insertion in the list can ta>e place at the following positions6 ? t the 6eginning of the li)t ? t the end of the li)t ? fter a gi8en element ? $efore a gi8en element In)ert at the 6eginning of the li)t" Qirst test whether the lin>ed list is initially empty. if yes. then the element is inserted as the first and only one element by performing the following steps6 ? Assign $M== value to the ne7t pointer and prev pointer field of the new node ? Assign address of new node to head and tail pointer variables. If the list is not empty. then the element is inserted as the first element of the list by performing the following steps6 ? Assign $M== value to the prev pointer field of the new node. ? Assign value of head variable 'the address of the first element of the e7isting list( to the ne7t pointer field of the new node. ? Assign address of the new node to prev pointer field of the node currently pointed by head variable. i. e. first element of the e7isting list. ? Qinally Assign address of the new node to the head variable. In)ert at the 6eginning of the li)t" Loid insertatbegining 'node DDhead. node DDtail. int item( node Dptr, ptr3'nodeD(malloc'si8eof'node((, ptrP+info3item, if'Dhead33$M==( ptrP+ne7t3ptrP+prev3$M==, Dhead3Dtail3ptr, else ptrP+prev3$M==, ptrP+ne7t3Dhead, !H Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat 'Dhead(P+prev3ptr, Dhead3ptr, 4 4 In)erting at the end of the li)t Qirst test whether the lin>ed list is initially empty. if yes. then the element is inserted as the first and only one element by performing the following steps6 ? Assign $M== value to the ne7t pointer and prev pointer field of the new node ? Assign address of new node to head and tail pointer variable. If the list is not empty. then element is inserted as the last element of the list by performing the following steps6 ? Assign $M== value to the ne7t pointer field of the new node. ? Assign value of the tail variable 'the address of the last element of the e7isting list( to the prev pointer field of the new node. ? Assign address of the new node to the ne7t pointer field of the node currently pointed by tail variable i.e last element of the e7isting list. ? Qinally assign the address of the new node to tail variable. In)ert at the end of the li)t" Loid insertatend 'node DDhead. node DDtail. int item( node Dptr, ptr3'nodeD(malloc'si8eof'node((, ptrP+info3item, if'Dhead33$M==( ptrP+ne7t3ptrP+prev3$M==, Dhead3Dtail3ptr, else ptrP+ne7t3$M==, ptrP+prev3Dtail, 'Dtail(P+ne7t3ptr, Dtail3ptr, 4 4 In)erting after a gi8en element" Loid insert afterelement 'node DDhead. node DDtail. int item. int after( node Dptr. Dloc, ptr3head, loc3search'ptr.after(, if'loc33$M==( return, ptr3'nodeD(malloc'si8eof'node((, ptrP+info3item, if'locP+ne7t33$M==( ptrP+ne7t3$M==, locP+ne7t3ptr, ptrP+prev3Dtail, !K Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat Dtail3ptr, 4 else ptrP+prev3loc, ptrP+ne7t3locP+ne7t, 'locP+ne7t(P+prev3ptr, locP+ne7t3ptr, 4 4 In)erting 6efore a gi8en element" Loid insertbeforeelement 'node DDhead. node DDtail. int item. int before( node Dptr. Dloc, ptr3head, loc3search'ptr.before(, if'loc33$M==( return, ptr3'nodeD(malloc'si8eof'node((, ptrP+info3item, if'locP+prev33$M==( ptrP+prev3$M==, locP+prev3ptr, ptrP+ne7t3Dhead, Dhead3ptr, 4 else ptrP+prev3locP+prev, ptrP+ne7t3loc, 'locP+prev(P+ne7t3ptr, locP+prev3ptr, 4 4 Deleting an element ? To delete an element from the list. first the pointer are set properly and then the memory occupied by the node to be deleted is deallocated 'freed(. ? The deletion in the list can ta>e place at the following positions. !. At the beginning of the list ". At the end of the list 5. After a given element :. 9efore a given element Deleting from the 6eginning of the li)t" An element from the beginning of the lists can be deleted by performing following steps6 ? Assign the value of head ' address of the first element of the list( to a temporary variable 'say ptr( ? Qurther there are two cases6 !. If there is only one element in the e7isting list. both head and tail variable are set to $M==. !R Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat ". If there are more than one element in the list then following steps are given below6 # Assign $M== value to the prev pointer field of the second node. # Assign address of the second node to head. 5. Eeallocate the memory occupied by the node pointed to by ptr. Deleting from the 6eginning of the li)t" Loid deletefrombegining' node DDhead. node DDtail( node Dptr, if'Dhead33$M==( return, ptr3Dhead, if'Dhead33Dtail( SDone element onlyDS Dhead3Dtail3$M==, else 'ptrP+ne7t(P+prev3$M==, Dhead3ptrP+ne7t, 4 free'ptr(, 4 Deleting from the end of the li)t" An element from the end of the list can be deleted by performing following steps6 ? Assign the value of tail ' address of the last element of the list( to a temporary variable 'say ptr( ? Qurther there are two cases6 !. If there is only one element in the e7isting list. both head and tail variable are set to $M==. ". If there are more than one element in the list then following steps are given below6 # Assign $M== value to the ne7t pointer field of the second last node. # Assign address of the second last node to tail. 5. Eeallocate the memory occupied by the node pointed to by ptr. Deleting from the end of the li)t" Loid deletefromend' node DDhead. node DDtail( node Dptr, if'Dhead33$M==( return, ptr3Dtail, if'Dhead33Dtail( SDone element onlyDS Dhead3Dtail3$M==, else 'ptrP+prev(P+ne7t3$M==, Dtail3ptrP+prev, 4 free'ptr(, 4 Deleting after a gi8en element" "A Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat Loid ideleteafterelement 'node DDhead. node DDtail. int item. int after( node Dptr. Dloc, ptr3head, loc3search'ptr.after(, if'loc33$M==( return, else if''locP+ne7t(P+ne7t33$M==( ptr3locP+ne7t, locP+ne7t3$M==, Dtail3loc, free'ptr(, 4 else ptr3locP+ne7t, locP+ne7t3ptrP+ne7t, 'ptrP+ne7t(P+prev3loc, free'ptr(, 4 4 Deleting 6efore a gi8en element" Loid ideleteafterelement 'node DDhead. node DDtail. int item. int before( node Dptr. Dloc, ptr3head, loc3search'ptr.before(, if'loc33$M==( return, else if''locP+prev(P+prev33$M==( ptr3locP+prev, locP+prev3$M==, Dhead3loc, free'ptr(, 4 else ptr3locP+prev, locP+prev3ptrP+prev, 'ptrP+prev(P+ne7t3loc, free'ptr(, 4 4 The doubly lin>ed list can be deleted either by heading from the beginning or from the end. The list can be deleted from the beginning by performing the following steps6 ? Assign the head pointer to a temporary variable. say ptr. ? Advance the head pointer to the ne7t node. ? Eeallocate the memory occupied by the node pointed to by ptr. "! Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat The above steps are repeated till the entire list is deleted. Qinally the tail pointer is set to $M== value. Deleting entire li)t Loid deletelist'node DDhead. node DDtail( node Dptr, while'DheadN3$M==( ptr3Dhead, Dhead3'Dhead(P+ne7t, free'ptr(, 4 Dtail3$M==, 4
STUDENT T S?S"
1. W!A to im"lement the doubl$ lin#ed list. Aerform the following o"erations on the lin#ed list: !ddition of a number after a "articular location. !ddition of a number before a "articular location /eletion of a number after a "articular location. /eletion of a number before a "articular location /eletion of the number given b$ the user. .ounting the no of nodes. /is"la$ing the lin#ed list from both head and tail.. !dding the numbers at the beginning of the lin#ed list. !dding the numbers at the end of the lin#ed list. 2. -iven a doubl$ lin#ed list whose elements are of t$"e integer2 write function that co"ies the even integer numbers in one list and odd integer numbers in another list. 3. Write a recursive function to reverse a doubl$ lin#ed list.
Practical No.@
_______________________________________________________________________ _ I!" Getting acquainted with =in>ed list '%ircular =in>ed =ist(.
#$JECTI%E
The goal of this lab is to help you become acquainted with how to create %ircular lin>ed list. insert elements into lin>ed list. traverse the lin>ed list. and delete elements from the lin>ed list. Circ5lar 'inked 'i)t A circular list is a linear lin>ed list. e7cept that the last element points to the first element. Qor non empty circular lin>ed list there are no $M== pointer. The memory declarations for representing circular lin>ed lists are the same as for linear lin>ed lists Propertie)" ? Can reach entire li)t from an7 node ? Need )pecial te)t for end of li)t ? U)ed a) 65ffer A %ircular =in>ed =ist is a special type of =in>ed =ist It supports traversing from the end of the list to the beginning by ma>ing the last node point bac> to the head of the list. ? %ircular lin>ed lists are usually sorted ? %ircular lin>ed lists are useful for playing video and sound files in /looping0 mode. ? They are also a stepping stone to implementing graphs. an important topic in computer graphics. >epre)entation of Circ5lar linked li)t &uppose we want to store the list of integer numbers. then the circular lin>ed list can be represented in memory with the following declarations. t7pedef )tr5ct nodet7pe ; int info2 )tr5ct nodet7pe -ne(t2 =node2 node -head2 The above declaration define a new data type. whose each element is of type nodetype and gives it a name node. ? ?
1201
12 +
1 +,
#peration on 'inear linked li)t) ? %reating an empty list ? Traversing a list ? &earching an element ? Inserting an element ? Eeleting an element
STUDENT T S?S"
1. W!A to im"lement the .ircular lin#ed list. Aerform the following o"erations on the lin#ed list: !ddition of numbers after a "articular location. /eletion of the number given b$ the user. .ounting the no of nodes. /is"la$ing the lin#ed list. !dding the numbers at the beginning of the lin#ed list. !""ending the numbers given b$ the users. 2. Write a function that removes all du"licate elements from a linear lin#ed list. 3. Write a function that creates a new circular linear lin#ed list b$ selecting alternate elements of a given circular linear lin#ed list.
Practical No.A
_______________________________________________________________________ _ I!" Getting acquainted with &tac>s.
#$JECTI%E
The goal of this lab is to help you become acquainted with how to create stac> '=IQF(. pushing elements into stac>. popping elements from the stac>. chec>ing stac> for overflow and underflow.
Stack)
? ? ? ? &tac> is one of the commonly used data structures. &tac> is also called last in first out '=IQF( system &tac> is a linear list in which insertion and deletion can ta>e place only at one end called top. This structure operates in much the same way as stac> of trays.
Stack of -rays
Department of CSE and IT, JUIT Waknaghat -he following fig#re ill#strate a stack, which can accommodate maxim#m of 10 elements fig#re shows stack after p#shing elements .,10,12,/,,0
2 . 1 0 , top + 2 1 0 0 /, 12 10 .
2 . 1 top 0 , + 2 1 0 ,, 2 0 /, 12 10 .
#peration) on )tack) ? Create)tack9):Bto create s as an empty stac> ? P5)h9),i:<<to push elementi onto stac> s. ? Pop9):Bto access and remove the top element of the stac> s ? Peek9):Bto access the top element of the stac>s without removing it from the stac> s. ? I)f5ll9):Bto chec> whether the stac> s is full ? i)empt7Bto chec> whether the stac> s is empty >epre)entation of )tack in memor7 ? >epre)entation of )tack 5)ing arra7" &uppose elements of the stac> are integer type and stac> can store ma7imum !A elements.. )define TAU !A typedef struct int top, int elements@TAUB, 4stac>, stac> s, ? Jere we have defined our own data type named stac>. ? Qirst element top will be used to inde7 top element ? Array elements hold the elements of the stac> ? =ast line declares variable s of type stac> ? In addition to the previous declaration. we will use the declaration t7pedef en5m ;fal)e, tr5e = $oolean2 This statement defined new data type named 9oolean which can ta>e value false or true.
10 12 /,
10 12
0 0 top
10 12 /,
,,
? ? ?
$efore Ce can 5)e a )tack, it i) to 6e initialiDed. ) the inde( of arra7 element) can take an7 8al5e in the range 1 to ! &<1, the p5rpo)e of initialiDing the )tack i) )er8ed 67 a))igning 8al5e <1 to the top of 8aria6le. Thi) )imple ta)k can 6e accompli)hed 67 the folloCing f5nction.
%oid create)tack9 )tack -p): ; p),<12 = Te)ting )tack for 5nderfloC 9oolean isempty'stac> Dps( if'psP+top33P!( return true, else return false, 4 or 9oolean is empty'stac> Dps( return ''psP+top33P!(Vtrue6false(, 4 Te)ting )tack for o8erfloC 9oolean isfull'stac> Dps( if'psP+top33TAUP!( return true, else return false, "K Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat 4 or 9oolean is empty'stac> Dps( return ''psP+top33TAUP!(Vtrue6false(, 4
Push Operation
4efore the p#sh operation, if the stack is empty, then the val#e of the top will (e /1and if the stack is not empty then the val#e of the top will (e the index of the element c#rrently on the top. -herefore we place the val#e onto the stack, the val#e of top is incremented so that it points to the new top of stack, where incoming element is placed. 5oid p#sh6stack 7ps, int val#e8 9 ps/:top;;< ps/:elements=ps/:top>?val#e< @
Pop Operation
-he element on the top of the stack is assigned to a local varia(le, which later on will (e ret#rned via the ret#rn statement. 'fter assigning the top element to a local varia(le, the varia(le top is decremented so that it points to a new top Int pop6stack 7ps8 9 int temp< temp?ps/:elements=ps/:top>< ps/:top//< ret#rn temp< @
Ceclaration of stack
-he linked list representation allows a stack to grow to a limit of the comp#terDs memory. Typedef struct nodetype { int info; struct nodetype *ne t; !stack; "tack *top; Bere I have defined my own data type named stack, which is a self referential str#ct#re and whose first element info hold the element of the stack and the second element ne t hold the address of the element #nder it in the stack. -he last line declares a pointer varia(le top of type stack.
top 0 /, 12 !
top ,, 2 0 /, 12 10 . !
&#sh operation
-o p#sh a new element onto the stack, the element is inserted in the (eginning of the linked list. void p#sh6stack 77top, int val#e8 9 stack 7ptr< ptr?6stack78malloc6siAeof6stack88< if6ptr??"%$$8 9 printf6FGn #na(le to allocate memory for new nodeHI8< printf6FGnpress any key to exit..I8< getch68< ret#rn< @ ptr/:info?val#e< ptr/:next?7top< 7top?ptr< @
&op operation
-o pop an element from the stack, the element is removed from the (eginning of the linked list. Int pop6stack 77top8 9 int temp< stack 7ptr< temp?67top8/:info< ptr?7top< 7top?67top8/:next< free6ptr8< ret#rn temp< @
Cispose a stack
4eca#se the stack is implemented #sing linked lists, therefore it is programmers Jo( to write the code to release the memory occ#pied (y the stack. #oid disposestack$stack **top% { stack *ptr; while$*top&'N(LL% { ptr'*top; *top'$*top%)*ne t; free$ptr%; ! !
STUDENT T S?S"
1. Write a menu driven "rogram to im"lement the various o"erations on a stac# re"resented using an arra$. 2. Write a menu driven "rogram to im"lement the various o"erations on a stac# re"resented using lin#ed list. Various operations are: ? Createstack(s)to create s as an em"t$ stac# ? ush(s,i)!!to "ush elementi onto stac# s. ? op(s)to access and remove the to" element of the stac# s ? eek(s)to access the to" element of the stac#s without removing it from the stac# s. ? "s#u$$(s)to chec# whether the stac# s is full ? isempt%to chec# whether the stac# s is em"t$
Practical No.E
_______________________________________________________________________ _ I!" Getting acquainted with Applications of &tac>s in e7pression evaluation.
#$JECTI%E
The goal of this lab is to help you become acquainted with how to implement infi7. postfi7 and conversion from infi7 to postfi7 notation.
'pplications of Stacks
Stacks are #sed to pass parameters (etween f#nctions. Kn a call to f#nction, parameter and local varia(les are stored on stack. Bigh level programming lang#ages, s#ch as &ascal c etc. that provide s#pport for rec#rsion #se stack for (ook keeping. In each rec#rsive call, there is need to save the c#rrent val#es of parameters, local varia(les and the ret#rn address. In addition to a(ove stack are #sed to solve the vario#s pro(lemsH. 1. &arenthesis checker 2. Lathematical notation translation
1. &olish 6prefix8 notation 2. 3everse polish 6postfix8 "otation
Parenthesis checker
&arenthesis checker is a program that checks whether a mathematical expression is properly parenthesiAed. *e will consider three sets of gro#ping sym(ols)
N -he standard parenthesis I6 8I N -he (races F9 @I N the (rackets F= >I For an inp#t expression, it verifies that for each left parenthesis, (races or racket, there is a corresponding closing sym(ol and the sym(ols are appropriately nested.
Infix notation
In this notation, the operator sym(ol is placed (etween its two operands. -o add ' to 4 we can write as ';4 or 4;' -o s#(tract C from R we write as R/C, (#t we can not write C/R as this operation is not comm#tative. In this notation we m#st disting#ish (etween 6';48QR and ';64QR8
STUDENT T S?S"
1. W!A that im"lements the infi7 to "ostfi7 notation. 4he "rogram should read an infi7 string consists of single al"habetic characters for variables2 "arentheses2 and the )2F2G2 and + o"erators% call the conversion function% and then "rint the resulting "ostfi7 e7"ression. 4o test $our "rogram transforms the following e7"ression with $our "rogram% a. /FC). b. !GC).G/ c. >!)C?G.F/GF). :A Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat 2. W!A to im"lement the "ostfi7 evaluation. 4he "rogram should read a "ostfi7 string consisting of onl$ multidigit numeric data and the )2 F2 G2 and + o"erators% call the evaluation function and then "rint the result. !fter each evaluation it should loo" and "rocess another evaluation. 1valuate the following e7"ressions with $our "rogram: 25 0 G 1& F * ) 1 2& 3 ) G &1 F 2 30 & ) G 15 F
Practical No.11
_______________________________________________________________________ _ I!" Getting acquainted with Wueues.
#$JECTI%E
The goal of this lab is to help you become acquainted with how to create queue. enqueue an dequeue.
F5e5e"
A queue is a line of persons waiting for their turn at some service counter. &ervice counter can be a tic>eting window of a cinema hall or tic>eting window of railway station etc. Eepending on the type of service provided by the service counter and number of person interested in service. there could be queue of varying lengths. The service at the service counter is provide on the first come first serve 'Q%Q&( basis. i.e.. in order of their arrival in the queue.
4#s Stop
S#ppose that at service co#nter, t1 #nits time is needed to provide a service to a single person and on average a new person arrive at the co#nter in t2 #nits of time. -he following possi(ilities may arise) 1. If t1Wt2, then the service co#nter will (e free for some time (efore a new person arrives at the service co#nter. Bence no V#e#e in this case. 2. If t1:t2, then service co#nter will (e (#sy for some time even after the arrival of a new person. -herefore this person has to wait for some time. Similarly other persons arriving at the service co#nter have to wait. Bence a V#e#e will (e formed. . If t1?t2, then as a person leaves the service co#nter, a new person arrives at the service co#nter. Bence no V#e#e in this case also.
Definition
' V#e#e is a linear list in which insertion can take place at one end of the list, called the rear of the list, and deletion can take place at other end called front of the list. 4ehavior of the V#e#e is FIFK system. In V#e#e terminology insertion and deletion operations are known as enV#e#e and deV#e#e operations.
,
front 0
12
12
front
2
rear
Operations on -ueues
-he following operations are performed on V#e#es) Create -ueue$-%.to create V#e#e as an empty V#e#e. /n-ue$-0i%.to insert element I in a V. De-ueue$-%.to access and remove an element of V#e#e V. Peek$-%.to access the first element of the V#e#e V witho#t removing it. 1sfull$-%.to check whether the V#e#e V is f#ll. 1se,pty$-%.to check whether the V#e#e V is empty.
2rray representation
-he following are the necessary declaration) 3define C2P2C1T4 56 typedef struct { int front; int rear; int ele,ents7C2P2C1T48; !-ueue; -ueue -; In addition to a(ove decoration we will #se the declaration typedef enu, {false0 true ! 9oolean;
1
1
12 .
2
2
+ , 0 1 . 2
12 .
12 .
10 11 20
It is not possi(le to enV#e#e more elements as s#ch, tho#gh two position in the linear V#e#e are vacant. -o overcome this pro(lem, the elements of the V#e#e are moved forward, so that the vacant positions are shifted toward the rear end. 0 1 2 + , 0 1 . 2 0 front 1 rear
12 .
10 11 20
-his diffic#lty of managing front and rear can (e overcome if we treat the V#e#e position with index 0 as a position that comes after position with index 2 i.e., we treat the V#e#e as circ#lar.
+ ,
Rirc#lar V#e#e
/1 front
/1 rear
0 1 1 . 2 0
+ , 2 . 2 12 0 front + rear 1 . 2 0 1 , 0 1
3epresentation of a V#e#e
+ , 2 . 2 12 2 front + rear 1 . 2 0 0 1
+ , 2 2 front 2 rear 1 0 1 10 11 . 20 2 0 2 . 2 12
3epresentation of a V#e#e
+ , 2 0 1 10 1 11 . 20 00 0 2 . 2 12
2 front
0 rear
12
12
12
10
11
OnV#e#e operation
void enV#e#e6V#e#e 7pV, int val#e8 9 node 7ptr< ptr?6node78malloc6siAeof6node88< ptr/:info?val#e< ptr/:next?"%$$< if6pV/:rear??"%$$8 Q7V#e#e initially empty7Q pV/:front?pV/:rear?ptr< else 6pV/:rear8/:next?ptr< pV/:rear?ptr< @
CeV#e#e operation
Int deV#e#e6V#e#e 7pV8 9 int temp< node 7ptr< temp?6pV/:front8/:info< ptr?pV/:front< if6pV/:front??pV/:rear8 Q7only one element7Q pV/:front?pV/:rear?"%$$< else pV/:front?6pV/:front8/:next< free6ptr8< ret#rn temp< @
Cisposing a V#e#e
5oid disposeV#e#e6V#e#e 7pV8 9 node 7ptr< while6pV/:frontZ?"%$$8 9 ptr?pV/:front< pV/:front?6pV/:front8/:next< free6ptr8< @ pV/:rear?6node78"%$$< @
STUDENT T S?S"
1. Write a menu driven "rogram to im"lementing the various o"erations on a linear queue. 2. Write a menu driven "rogram to im"lementing the various o"erations on a .ircular queue. 3. Write a menu driven "rogram to im"lementing the various o"erations on a queue re"resented using a lin#ed list. Harious o"eration are% enqueue data into queue <! Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat dequeue and "rint data "rint data at the front "rint data at the rear "rint entire queue "rint queue status: em"t$ "rint queue status : full "rint number of elements.
Practical No.11
_______________________________________________________________________ _ I!" Getting acquainted with Applications of queues in e7pression evaluation.
#$JECTI%E
The goal of this lab is to help you become acquainted with how to evaluate prefi7 e7pression.
STUDENT T S?S"
1. Ine wa$ to evaluate a "refi7 e7"ression is to use a queue. 4o evaluate the e7"ression2 scan it re"eatedl$ until $ou #now the final e7"ression value. In each scan read the to#ens and store them in a queue. In each scan re"lace an o"erator that is followed b$ two o"erands with their calculated values. For e7am"le2 the following e7"ression is a "refi7 e7"ression that is evaluated to 15D P ) G D ) 2 8 G ) & 8 * 3 we scan the e7"ression and store it in a queue. /uring the scan when an o"erator is followed b$ two o"erands2 such as ) 2 8 2 we "ut the result 1@ in the queue after the first scan we have P ) G D 1@ G 12 * 3 after the second scan we have P ) D@ 02 3 after the third scan we have P 1*2 3 after the fourth scan we have 15D &rite a c pro'ram to eva$uate a pre#i( e(pression.
Practical No.10
_______________________________________________________________________ _ I!" Getting acquainted with Trees. 9inary trees and 9&T..
#$JECTI%E
The goal of this lab is to help you become acquainted with how to create binary tree or 9&T. traverse binary tree or 9&T 'prePorder. inPorder. postPorder(. inserting. deleting. searching. and finding height in binary tree or 9&T.
-3OO COFI"OC
' tree - is a finite non empty set of elements. Kne of these elements is called the root, and the remaining elements, if any, are portioned into trees, which are called the s#( trees of -.
Introd#ction to -ree
F#ndamental data storage str#ct#res #sed in programming. Rom(ines advantages of an ordered array and a linked list. Searching as fast as in ordered array. Insertion and deletion as fast as in linked list.
-ree characteristics
Ronsists of nodes connected (y edges. "odes often represent entities 6complex o(Jects8 s#ch as people, car parts etc. Odges (etween the nodes represent the way the nodes are related. Its easy for a program to get from one node to another if there is a line connecting them. -he only way to get from node to node is to follow a path along the edges.
-ree -erminology
Boot; node witho#t parent 6'8 1nternal node; node with at least one child 6', 4, R, F8 / ternal node 6a.k.a. leaf 8) node witho#t children 6O, I, S, T, U, B, C8 2ncestors of a node; parent, grandparent, grand/grandparent, etc. Depth of a node) n#m(er of ancestors E Cei:ht of a tree; maxim#m depth of any node 6 8 Descendant of a node; child, grandchild, grand/grandchild, etc. De:ree of an ele,ent; no. of children it has "ubtree; tree consisting of a node and its descendants
A
subtree
I J K
-ree -erminology
Path; -raversal from node to node along the edges res#lts in a seV#ence called path. Boot; "ode at the top of the tree. Parent; 'ny node, except root has exactly one edge r#nning #pward to another node. -he node a(ove it is called parent. Child; 'ny node may have one or more lines r#nning downward to other nodes. "odes (elow are children. Leaf; ' node that has no children. "ubtree; 'ny node can (e considered to (e the root of a s#(tree, which consists of its children and its childrenDs children and so on.
-ree -erminology
#isitin:; ' node is visited when program control arrives at the node, #s#ally for processing. Tra=ersin:; -o traverse a tree means to visit all the nodes in some specified order. Le=els; -he level of a partic#lar node refers to how many generations the node is from the root. 3oot is ass#med to (e level 0. Deys; Tey val#e is #sed to search for the item or perform other operations on it.
4inary -rees
Overy node in a (inary tree can have at most two children. -he two children of each node are called the left child and right child corresponding to their positions. ' node can have only a left child or only a right child or it can have no children at all.
4inary -rees
' (inary tree is a tree with the following properties)
N Oach internal node has at most two children 6exactly two for proper (inary trees8 N -he children of a node are an ordered pair
'pplications)
N arithmetic expressions N decision processes N searching
A
*e call the children of an internal node left child and right child 'lternative rec#rsive definition) a (inary tree is either
N a tree consisting of a single node, or N a tree whose root has an ordered pair of children, each of which is a (inary tree
D
TB//"
4inary Search -rees) ' (inary search tree - is a (inary tree that may (e empty. ' non empty (inary search tree satisfies the following properties) 1. Overy element has a key 6or val#e8 and no two elements have the same key i.e. all keys are #niV#e. 2. -he keys, if any, in the left s#(tree of the root are smaller than the key in the node. . -he keys, if any, in the right s#(tree of the root are larger than the key in the node. +. -he left and right s#(trees of the root are also (inary search trees.
9"T
10 00 1, .0 22 10 +0 ,, 1, 10 .0 22
02
12
Fig.6a8
Fig. 6(8
Fig. [
'rray 3epresentation
For simplicity , I am considering the array is indexed with an index set (eginning from 1 not 0.
1 10 2 00 .0 + 0 , 02 0 1, 1 22
1 +0
'rray representation of 4S- in fig 6a8 2 + , 0 10 ,, , 12 'rray representation of 4S- in fig 6(8 2 + , 0 .0 1, 'rray representation of 4S- in fig 6c8
1 10
1 22
Linked representation
-he most pop#lar and practical way of representing a (inary tree is #sing links 6pointers8.
10
00
.0
0 !
! 02 !
! 1, !
! 22 !
2rray Bepresentation
In this representation the (inary tree is represented (y storing each element at the array position corresponding to the n#m(er assigned to each n#m(er 6nodes8 In this representation, a (inary tree of height h reV#ires an array of siAe 62h/18, in the worst case
$inked representation
! 10
.0
! 1, !
! 22 !
$inked representation
! 10
! 12
! .0
! ., !
$inked 3epresentation
In linked representation, each element is represented (y a node that has exactly two link fields. Field names are left and right. Oach node has data field called info. -he node str#ct#re is defined as) str#ct nodetype 9 str#ct nodetype 7left< int info< str#ct nodetype 7right< @<
1N)Order Tra=ersal
void inorder64S- 7tree8 9 if6treeZ?"%$$8 9 inorder6tree/:left8< printf6FPdI,tree/:info8< inorder6tree/:right8< @ @
Oxample
&re/order) ' 4 C O U B R F In order) C 4 U O B ' R F Craw the (inary tree -.
Oxample
Pre) Order; ' 3oot In) Order; 4 C U 4 C O U B R F
Oxample)
&artial -ree
'
$-'
3-'
C 4 O B
4 C C 4 O U U O
B B
Oxample
Pre) Order; 4 3oot In) Order; C $eft s#(tree $-4 C O U B
Oxample)
&artial -ree
'
4 3-'
R
C
U O B
3-4
O U
U O
B B
Oxample
Pre) Order; O 3oot In) Order; U $eft s#(tree $-O U B
Oxample)
&artial -ree
'
4 3-'
R
C O
R R
F F
Oxample
Pre) Order; R 3oot In) Order; $eft s#(tree $-R F
Oxample)
'
4S,0 1,
2,
20
+0
00
.0
10
+,
0,
.,
Searching an element
-he element in (inary search tree can (e searched very V#ickly. Search operation on (inary tree is similar to applying (inary search techniV#e to a sorted linear array. -he element to (e searched will (e compared with root node. If matches with the root node then search terminates here. Ktherwise search is contin#ed in the left s#( tree if the element is less then the root or in the right s#( tree if the element is greater then the root.
"
!A
&uppose I try to find the node with H in it. Qirst go down the right subtree. then go down the left subtree.
Searching an element
4S- searchelement64S- 7tree, int val#e8 9 if66tree/:info??val#e8\\tree??"%$$8 ret#rn tree< else if6val#eWtree/:info8 ret#rn searchelement6tree/:left, val#e8< else ret#rn searchelement6tree/:right, val#e8< @
"
!A
Thi) f5nction ret5rn) a pointer to the node containing the )malle)t element in the tree. It doe) )o 67 folloCing the left )ide of the tree.
"
!A
Thi) f5nction ret5rn) a pointer to the node containing the large)t element in the tree. It doe) )o 67 folloCing the right )ide of the tree.
Deletin: a node
-o delete a node, the following possi(ilities may arise) Node is ter,inal node) in this case if node is left child of its parent, then the left pointer of its parent is set to "%$$, otherwise it will (e right child of its parent and accordingly pointer of its parent is set to "%$$. Node ha=in: only one child; in this case, the appropriate pointer of its parent is set to child, th#s (y passing it. Node ha=in: two children; predecessor replaces node val#e, and then the predecessor of node is deleted.
4S,0 1,
2,
20
+0
00
.0
10
+,
0,
.,
4S,0
2,
20
+0
00
.0
10
+,
0,
.,
4S,0 .0
2,
20
+0
00
10
+,
0,
.,
"ince node has both ri:ht and left child0 if ri:ht sub tree is opted find the s,allest node0 if left sub tree is opted find the lar:est node
4S,0 .0
2,
20
+0
00
.,
10
+,
0,
"ince node has child0 if ri:ht sub tree is opted find the s,allest node0 if left sub tree is opted find the lar:est node
4S-) Celetion
Deleting a node with one hild
Before delete(4)
After delete%2&
Before delete(2)
Deletion !trateg"# 'e$la e the node with s(allest node in the right subtree
4S,0 .0
2,
20
+0
00
.,
10
+,
0,
"ince node)*ri:ht'node)*left'N(LL0 delete the node and place N(LL in the parent node
!A
3emovalH
Droot < t " t right ; H !A ; H !A R " R < Droot
&et t 3 t right
3emovalH
If the node to (e removed has two children, the general strategy is to replace the data of this node with the smallest data of the right s#(tree. -hen the node with the smallest data is now removed 6this case is easy since this node cannot have two children8.
3emovalH
Remove the " againX Droot < < Droot
"
!A
!A
5 :
5 :
STUDENT T S?S"
1. Write a com"lete menu driven "rogram to demonstrate the use of the different o"erations discussed in the binar$ tree descri"tion. For e7am"le P creation P traversal o "re o in o "ost P deletion P searching RK Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat 2. Write a function to "erform the level order traversal of a binar$ search tree. 5. Write a function to find the "redecessor and successor of a given element.
Practical No.1/
_______________________________________________________________________ _ I!" Getting acquainted with &orting 'Insertion and &election &ort(.
#$JECTI%E
The goal of this lab is to help you become acquainted with how to arrange the elements in an ascending or descending order.
Sorting"
&orting is the process of arranging the elements in some logical order. ? &orting are classified into following categories6 ? E(ternal )orting" ? deals with sorting of the data stored in data files. This method is used when the volume of data is very large and cannot be held in computer main memory. ? Internal )orting" ? deals with sorting the data held in memory of the computer
Selection Sort"
The selection sort also requires 'nP!( passes to sort an array. In the first pass. find the smallest element from elements a@AB. a@!B. a@"B.X... a@nP!B and swap with the first element. i.e. a@AB. In the second pass. find the smallest element from elements a@!B. a@"B. a@5B.. a@nP!B and swap with a@!B and so on. Pa))1. ? Qind the location loc of the smallest element in the entire array. i.e. a@AB.@!B.a@"BX a@nP!B ? Interchange a@AB 2 a@locB. Then a@AB is trivially sorted. Pa))0. ? Qind the location loc of the smallest element in the entire array. i.e. a@!B.a@"BX a@nP!B ? Interchange a@!B 2 a@locB. Then a@AB. a@!B are sorted. Pa))k. ? Qind the location loc of the smallest element in the entire array. i.e. a@>B.a@>Y!B.a@>Y"BXa@nP!B ? Interchange a@>B 2 a@locB. Then a@AB.a@!B.a@"B.Xa@>B are sorted. Pa))n<1. ? Qind the location loc of the smaller of the element a@nP"B.a@nP!B ? Interchange a@nP"B 2 a@locB. Then elements a@AB.a@!B.a@"BX.a@nP!B.
E& !P'E"
Given array6 "A 5; :A !AA 5 !A !; a@AB a@!B a@"B a@5B a@:B a@;B a@<B !AA Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
"A
5;
a@"B :A
a@5B !AA
a@:B 5
a@;B !A
a@<B !;
"election "ort
Pass H
$oc?,
$oc?0
Pass I
$oc?+
"election "ort
Pass E
$oc?,
Pass J
$oc?0
'lgorithm
Smallestelement6a,n,k,loc8 Bere a is linear array of siAe n. this s#( algorithm finds the location loc of smallest element among a=k/1>,a=k;1>,a=k;2>Ha=n/1>. -emporary varia(le small is #sed to hold the c#rrent smllest element nd J is #sed loop control varia(le. 4egin set small?a=k/1> set loc?k/1 for J?k to 6n/18 (y 1 do if6a=J>Wsmall8 then set small ? a=J> set loc?J endif endfor end
'lgorithm
Selectionsort6a,n8 Bere a is the linear array with n elements in memory. -his algorithm sorts elements into ascending order. It #ses a temporary varia(le temp to facilitate the exchange of two val#es and varia(le I is #sed loop control varia(le 4egin for i?1 to 6n/18 (y 1 do call smllest element6a,n,I,loc8 set temp?a=i/1> set a=i/1>?a=loc> set a=loc>?temp endfor end
1nsertion sort
-his algorithm is very pop#lar with (ridge players when they sort their cards. In this proced#re, we pick #p a partic#lar val#e and then insert it at the appropriate place in the sorted s#( list. -his algorithm also reV#ires n/1 passes
1nsertion sort
Pass5) a=1> is inserted either (efore or after a=0> so that a=0> and a=1> are sorted. PassH; a=2> is inserted either (efore a=0> or (etween a=0> and a=1> or after a=1> so that the elements a=0>, a=1>, a=2> are sorted. Pass3; a= > is inserted either (efore a=0> or (etween a=0> and a=1> or (etween a=1> and a=2> or after a=2> so that the elements a=0>, a=1>, a=2>, aa= > are sorted. Passk; a=k> is inserted in proper place in the sorted s#( array a=0>, a=1>, a=2>,Ha=k/1> so that the elements a=0>, a=1>, a=2>,Ha=k/1>,a=k> are sorted. Passn)5; a=n/1> is inserted in proper place in the sorted s#( array a=0>, a=1>, a=2>,Ha=n/2> so that the elements a=0>, a=1>, a=2>,Ha=n/1> are sorted.
/ a,ple
Uiven array) 20 , +0 100 a=0> 20
Pass 5;
a=1> , a=2> +0
a=0> ,
a=1> 20
a=,> 10
"election "ort
Pass H
Pass I
Since =+> is less than a= >,a=2>,aa=1> as well as a=0> therefore insert a=+> (efore a=0>
"election "ort
Pass E
Since =,> is less than a=+>,a= >,a=2>,a=1> therefore insert a=,> (efore a=1>
Pass J
Since =0> is less than a=,>, a=+>,a= >,a=2> therefore insert a=,> (efore a=2>
'lgorithm
insertionsort6a,n8 Bere a is the linear array with n elements in memory. -his algorithm sorts elements into ascending order. It #ses a temporary varia(le temp to facilitate the exchange of two val#es and varia(le J and k are #sed loop control varia(les. 4egin for k?1 to 6n/18 (y 1 do set temp?a=k> set a=J>?k/1 while66tempWa=J>8 and J:?08 do set a=J;1>?a=J> set J?J/1 endwhile set a=J;1>?temp endfor end
STUDENT T S?S"
1. !n arra$ contains the elements shown below. =ort the elements b$ insertion sort in ascending order2 what would be the value of the elements in the arra$ after each "asses of the straight insertion sort algorithm. 3 13 0 2* && 23 D8 50 2. !n arra$ contains the elements shown below. =ort the elements b$ selection sort in ascending order2 what would be the value of the elements in the arra$ after each "asses of the straight selection sort algorithm. 0 8 2* && 13 23 D8 50 3 3. 5odif$ the e7ercise1 and e7ercise2 given above for sorting in descending order. !A; Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Practical No. 1.
_______________________________________________________________________ _ I!" Getting acquainted with &orting '9ubble and Terge &ort(.
#$JECTI%E
The goal of this lab is to help you become acquainted with how to arrange the elements in an ascending or descending order.
$566le Sort"
? ? ? ? It requires nP! passes to sort an array. In each pass every element a@iB is compared with a@iY!B. for i3A to 'nP>(. where > is the pass number and if they are out of order i. e. if a@iB+a@iY!B. they are swapped. This will cause the largest element move up or bubble up. Thus after the end of the first pass the largest element in the array will be placed in the nth position and on each successive pass. the ne7t largest element is placed at position 'nP!(.'nP"(X.." respectively
Pa))1. &tep!. if a@AB+a@!B then swap a@AB and a@!B. &tep". if a@!B+a@"B then swap a@!B and a@"B. &tepnP!. if a@nP"B+a@nP!B then swap a@nP"B and a@nP!B. Pa))0. &tep!. if a@AB+a@!B then swap a@AB and a@!B. &tep". if a@!B+a@"B then swap a@!B and a@"B. &tepnP". if a@nP5B+a@nP"B then swap a@nP5B and a@nP"B. . . Pa)) k. &tep!. if a@AB+a@!B then swap a@AB and a@!B. &tep". if a@!B+a@"B then swap a@!B and a@"B. &tep nP>. if a@nP>Y!B+a@nP>B then swap a@nP>Y!B and a@nP>B. Pa)) n<1 &tep ! if a@AB+a@!B then swap a@AB and a@!B.
9ubble sort
Oxample) 12 +0 2 1,
12 +0 2 1,
Uiven array
12 +0 2 1,
Pass 5
12 +0 2 1,
12 2 +0 1,
12 2 1, +0
9ubble sort
2 2 12 1, +0 +0 2
12 1,
12 1, +0
&ass
pass +
'lgorithm
4#((lesort6a,n8 for k?1 to 6n/18 (y 1 do for J?0 to 6n/k/18 (y 1 do if6a=J>:a=J;1>8 then set temp?=J> set a=J>?a=J;1> set a=J>?temp endif endfor Ondfor end
!erge Sort"
LergeSort 6Oxample8 / 1
LergeSort 6Oxample8 / 2
LergeSort 6Oxample8 /
LergeSort 6Oxample8 / +
LergeSort 6Oxample8 / ,
LergeSort 6Oxample8 / 0
LergeSort 6Oxample8 / 1
LergeSort 6Oxample8 / .
LergeSort 6Oxample8 / 2
LergeSort 6Oxample8 / 10
LergeSort 6Oxample8 / 11
LergeSort 6Oxample8 / 12
LergeSort 6Oxample8 / 1
LergeSort 6Oxample8 / 1+
LergeSort 6Oxample8 / 1,
LergeSort 6Oxample8 / 10
LergeSort 6Oxample8 / 11
LergeSort 6Oxample8 / 1.
LergeSort 6Oxample8 / 12
LergeSort 6Oxample8 / 20
LergeSort 6Oxample8 / 21
LergeSort 6Oxample8 / 22
Strategy
N (reak pro(lem into similar 6smaller8 s#(pro(lems N rec#rsively solve s#(pro(lems N com(ine sol#tions to answer
STUDENT T S?S"
1. !n arra$ contains the elements shown below. 4he first two elements have been sorted using a bubble sort. What would be the value of the elements in the arra$ after three more "asses of the bubble sort algorithmJ Ese the version of bubble sort that start from the end and bubbles u" the smallest element. 0 8 2* && 13 23 50 D8 2. =how the result after each merge "hase when merging the following two files * 12 1D 23 3& 8 11 10 2@ 25 13 21 20 28 2D 0 3@ 3* 30 3D
Practical No. 1*
_______________________________________________________________________ _ I!" Getting acquainted with &orting 'Radi7 and Wuic> &ort(.
#$JECTI%E
The goal of this lab is to help you become acquainted with how to arrange the elements in an ascending or descending order.
F5ick Sort"
? Another dividePandPconquer sorting algorithm ? To understand quic>Psort. let s loo> at a highPlevel description of the algorithm !( Eivide 6 If the sequence & has " or more elements. select an element 7 from & to be your pivot. Any arbitrary element. li>e the last. will do. Remove all the elements of & and divide them into 5 sequences6 =. holds & s elements less than 7 I. holds & s elements equal to 7 G. holds & s elements greater than 7 "( Recurse6 Recursively sort = and G 5( %onquer6 Qinally. to put elements bac> into & in order. first inserts the elements of =. then those of I. and those of G. Jere are some diagrams....
2% Di=ide) rearrange elements so that x goes to its final position O 8 Becurse and Con-uer) rec#rsively sort
In/&lace M#ick/Sort
Divide step: l scans the sequence from the left, and r from the right.
A swap is performed when l is at an element larger than the pivot and r is at one smaller than the pivot.
2l:orith,
V#icksort6a , l, r8 4egin If6lWr8 then splitarray6a,l,r,loc8 V#icksort6a,l,loc/18 V#icksort6a,loc;1,r8 endif end
QQpartition the array QQrec#rsively sort left s#( array QQrec#rsively sort right s#( array
>adi( Sort"
This method is used by the most of the of the people when sorting a list of names in alphabetical order. The procedure we follow is6 Qirst. the names are grouped according to the first letter. thus the names are arranged in "< classes. one for each letter of the alphabet.. first class consists of those names that begin with letter A. the second class consists of those names that begin with letter 9 . and so on. $e7t. the names are grouped according to the second letter. After this step. the list of names will be sorted on first two letters. This process is continued for the number of times depending on the length of the names with ma7imum letters. If shorter names. we assume those names padded with blan>s. !"5 Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
E& !P'E"
Cho wantZs to sort bytesV [ouV I norally sort asciiPte7ts. floats or longints. 9ecause I only want to e7plain how the e7tenstion wor>s IZll go on with longints. If you want increase the si8e of the elements to sort you can do this in several ways. Iither you increase the si8e of inde7 and distribution or you sort in several passes. Increasing the si8e of the inde7 only wor>s for short values 'sorting smallints would require at least <;;5<D" bytes for inde7 and distribution list which finally needs ";< >b of memory.. I thin> this is to much 'only thin> about how long it ta>es to clear the memory and build the inde7Plist.. In this time quic>sort may have sorted your list already((. $ow we need a clever way to sort more bits with the same memoryPamount. Ce can do this with several passes. =etZs do it in decimal.
unsorted list: 523 153 088 554 235 sorting for R di! 0 (le st signifi" nt digit) 523 153 554 235 088 # sorting for R di! 1 (2nd$ signifi" nt digit) 523 235 153 554 088 # sorting for R di! 2 (%ost$ signifi" nt digit) 088 153 235 523 554
STUDENT T S?S"
1. !n arra$ contains the elements shown below. What would be the value of the elements in the arra$ after each "ass of the quic# sort algorithmJ !lso mention the "ivot. 5 3 8 D 1 0 @ 2 * & 2. =ort the list 213 1&5 &5* 0@@ 515 2D5 *0& D25 using buc#et sort method.
Practical No.13
_______________________________________________________________________ _
'inear Search"
? ? This method. which traverse a sequentially to locate item is called linear search or sequential search. The algorithm that one chooses generally depends on organi8ation of the array elements. if the elements are in random order. then one have to use linear search technique
lgorithm"
=inearsearch'a.n.item.loc( Jere a is the linear array of the si8e n. this algorithm finds the location of the elemnts item in linear array a. if search ends in success it sets loc to the inde7 of the element, otherwise it sets loc to P! 9egin for i3A to 'nP!( by ! do if'a@iB 3 item( then set loc3I e7it endif endfor set loc P! end
$inar7 Search"
&uppose the elements of the array are sorted in ascending order. The best sorting algorithm. called binary search. is used to fined the location of the given element !"< Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
E& !P'E"
5.!A.!;."A.5;.:A.<A Ce want to search element !; Given array !. Ce ta>e the beg3A. end3< and compute location of the middle element as mid3'begYend(S" 3 'AY<(S"35 ". %ompare the item with mid i.e. a@midB3a@5B is not equal to !;. beg*end. Ce start ne7t iteration. 5. As a@midB3"A+!;. therefore. we ta>e end3midP!35P!3" where as beg remains same.. Thus mid3'begYend(S" 3 'AY"(S"3! &ince a@midB i.e. a@!B3!A*!;. therefore. we ta>e beg3midY!3!Y!3". where as end remains same &ince beg3end :. %ompute the mid element mid3'begYend(S"3'"Y"(S"3" &ince a@midB i.e. a@"B3!;. the search terminates on success.
lgorithm"
9inarysearch'a.n.item.loc( 9egin set beg3A set end3nP! &et mid3'begYend(S" while''beg*3end( and'a@midBN3item( do if'item*a@midB( then set end3midP! else set beg3midY! endif set mid3'begYend(S" endwhile if'beg+end( then set loc3P! else set loc3mid endif end
STUDENT T S?S"
1. !n arra$ contains the elements shown below. Esing the binar$ search algorithm2 trace the ste"s followed to find 88. !t each loo" iteration2 including the last2 show the contents of first2 last and mid. 18 13 10 2* && 5* 88 D0 2. !n arra$ contains the elements shown below. Esing the binar$ search algorithm2 trace the ste"s followed to find 2@. !t each loo" iteration2 including the last2 show the contents of first2 last and mid. !"H Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Department of CSE and IT, JUIT Waknaghat 18 13 10 2* && 5* 88 D0 3. Write a "rogram that creates an arra$ of 1@@ random integers in the range 1 to 2@@ and then2 using the sequential search2 searches the arra$ 1@@ times using randoml$ generated targets in the same range at the end of the "rogram2 dis"la$ the following statistics% a. the number of searches com"leted b. the number of successful searches c. the "ercentage of successful searches d. the average number of tests "er search to determine the average number of test "er search2 $ou need to count the number of tests for each search.
Practical No.1@
_______________________________________________________________________ _ I!" Getting acquainted with Jeap.
#$JECTI%E
The goal of this lab is to help you become acquainted with how to create JIA\. and sort the array by using heap sort.
Ceaps
ObKecti=es; Cescri(e a heap Cescri(e how a heap can (e represented in memory Implement the vario#s operations on heap Cescri(e the applications of heaps
1ntroduction
Beap is (inary tree that satisfies the following properties) Shape property Krder property 4y the shape property we mean that heap m#st (e complete (inary tree. 4y order property we mean that every node in the heap, the val#e stored in that node is greater than or eV#al to the val#e in each of its children. ' heap that satisfy the a(ove property is known as ,a ? heap? if every node in the heap is less than or eV#al to the val#e in each of its children. that heap is known as ,in? heap?
Ceaps
20 , 21 2, +0 21 ,0
,0 +0
2,
20
Li:?$a% +a ? heap
2,
20
Operation on heaps
Deletin: an ele,ent fro, the heap; Olement from the heap is always deleted from root of the heap. If we delete element from the root it create hole, vacant space , in root position 4eca#se heap m#st (e complete, we fill the hole with the last element of the heap.
2,
20
"tartin: heap
+0 21
2,
20
2,
20
'ssign the val#e of the root to the temporary varia(le, which may (e reV#ired for f#rther processing. 4ring the last element of the heap to the root node position. 3ed#ce the siAe of the heap (y factor of one. 'pply reheapify downward operation from root node.
2,
20
"tartin: heap
2,
20
2dd =alue M6
2,
20
2,
20
Department of CSE and IT, JUIT Waknaghat 5oid reheapify%pward6int heap=>,int start8 9 int temp, parent< if6start:18 9 parent?startQ2< if6heap=parent>Wheap=start>8 9 temp?heap=start>< heap=start>?heap=parent>< heap=parent>?temp< reheapify%pward6heap,parent8 @ @ @
The insertion of an ele,ent into heap is done usin: the followin: steps;
Increase the siAe of the heap (y a factor of 1. Insert the element as the last element of the heap. 'pply reheapify #pward operation from the last node.
2pplications of Ceaps
1,ple,entin: a priority -ueue "ortin: an array usin: efficient techni-ue known as heap sort
Priority <ueues
-he priority V#e#e is a data str#ct#re in which the intrinsic ordering of the data items determines the res#lt of its (asic operation. -he priority V#e#e can (e classified in two types) 1.'ssending priority V#e#e 2.Cescending priority V#e#e
9uildin: a Ceap
4efore we can apply heap sort techniV#e for sorting an array, the first task is to (#ild a heap i.e. convert an #nsorted array into a heap.
1 2
+ , 0 1
10 , 10 1, 12 , ,0
10 , , 10 ,0
1,
12
4#ilding a heap
10 , , 10 ,0
1,
12
10
10
1,
2rray
12
,0
4#ilding a heap
10 1, , 10 ,0
12
10
1,
10
,
2rray
12
,0
4#ilding a heap
10 1, , ,0 10
12
10
1,
,0
,
2rray
12
10
4#ild Beap
Ceapify$a0n% Bere a is the linear array with siAe n. this algorithm (#ilds max. heap 4egin set index?parent of the node with index n for i?index to 1 (y /1 do call reheapify #pward6a,i,n8 endfor Ond
4#ild Beap
5oid heapify6int a=>, int n8 9 int i,index< index?nQ2< for6i?index<i:?1<i//8< reheapify%pward6a,i,n8< @
Ceap "ort
Neneral approach of heap sort; 1. From the given array (#ild the initial max heap. 2. Interchange the root 6maxim#m8 element with the last element. . %se reheapify downward operation from the root node to re(#ild the heap of the siAe one less then the starting. +. 3epeat steps 1 and 2 #ntil there are no more elements.
example
Initial elements are) 10, ,, 10, 1,, 12, ,, ,0 'fter heapify operation)
1 2 + , 0 1
10
1,
,0
12
10
10 ,0 10 , 12 1, , 12 10 10 , ,
1, 1, 1, 1, 1, 12 12 , , , 10 10
,0 , , 10 10 10 10 10 12 12 12 12
, , , , , , 1, 1, 1, 1, 1, 1,
12 12 12 12 , , , , , , , ,
, 10 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0
10 10 10 10 10 10 10 10 10 10 10 10
Beap sort
Ceapsort$a0n% Bere a is the linear array of siAe n in memory. -his algorithm sorts this array in ascending order #sing heap sort method. 4egin call heapify6a,n8 for i?n to 2 (y /1 do interchange elements a=1> and a=i> call reheapifydownward6a,1,i/18 endfor end
Beap sort
5oid heapsort6int a=>,int n8 9 int i,temp< heapify6a,n8< for6i?n<i:1<i//8 9 temp?a=1>< a=1>?a=i>< a=i>?temp< reheapifydownward6a,1,i/18< @ @
STUDENT T S?S"
1. Write a com"lete c "rogram to create 5a7. Kea" of the following sequence 32 02 &2 *2 132 1@2 12 52 02 11 2. Write a function to delete an item at inde7 i from Kea". 3. Write a c "rogram to sort the following sequence b$ using hea" sort. 1@2 52 0@2 152 122 352 5@
Practical No.1A
_______________________________________________________________________ _ I!" Getting acquainted with Graphs.
#$JECTI%E
The goal of this lab is to help you become acquainted with how to Graphs and various operations on graphs li>e 9Q& and &Q& etc. !:H Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi
Nraphs
ObKecti=es; Cescri(e a graph Cescri(e how graph can (e represented in memory Implements the vario#s operations on graphs Cescri(e applications of graphs
1ntroduction
Uraph is another important non linear data str#ct#re. -his data str#ct#re is #sed to represent relationship (etween pairs of elements, which are not necessarily hierarchical in nat#re. ' graph is defined as) FUraph U is a ordered set 65,O8, where 56U8 represent the set of elements, called vertices, and O6U8 represents the edges (etween these vertices.I Uraphs can (e
N %ndirected N Cirected
Nraphs
Fig#re shows a sample graph 56U8?9v1,v2,v ,v+,v,@ O6U8?9e1,e2,e ,e+,e,@
e2 v1 v, e e, v+
e1
v2
e+
Nraph
e2 v1 v, e e, v+
e1
v2
e+
In directed graph, an edge is represented (y an ordered pair 6#,v8 6i.e.?6#,v88, that can (e traversed only from # toward v.
Nraph Ter,inolo:y
2dKacent #ertices; 's an edge e is represented (y pairs of vertices denoted (y =#,v>. -he vertices # and v are called endpoints of e. these vertices are also called adJacent vertices or neigh(ors. De:ree of a =erte ) -he degree of vertex #, written as deg6#8, is the n#m(er of edges containing #. If deg6#8?0, this means that vertex # does not (elong to any edge, then vertex # is called an isolated vertex.
Nraph Ter,inolo:y
Path; ' path & of length n from a vertex # to vertex v is defined as seV#ence of 6n;18 vertices i.e. &?6v1,v2,v ,HHvn;18 S#ch that #?v1, v?vn;1 -he path is said to (e closed if the endpoints of the path are same i.e. v1?vn;1. -he path is said to (e simple if all the vertices in te seV#ence are distinct, with the exception that v1?vn;1.In that case it is known as closed simple path.
Nraph Ter,inolo:y
Cycle; ' cycle is closed simple path with length two or more. Sometimes, a cycle of length k 6i.e. k distinct vertices in the path8 is known as k/cycle. Connected Nraph; ' graph is said to (e connected if there is path (etween any two of its vertices, i.e. there is no isolated vertex. 2 connected :raph without any cycles is called a tree? Thus we can say that tree is a special :raph?
Nraph Ter,inolo:y
Co,plete Nraph; ' graph U is said to (e complete or f#lly connected if there is a path from every vertex to every other vertex. ' complete graph with n vertices will have n6n/18Q2 edges.
Nraph Ter,inolo:y
Oei:hted Nraph; ' graph is said to (e weighted graph if every edge in the graph is assigned some data. -he weight is denoted (y w6e8. w6e8 is non negative val#e that may (e representing the cost of moving along that edge or distance (etween the vertices.
2 0 1 1 + , + 2 2 ,
2 + 0
Nraph Ter,inolo:y
+ultiple /d:es; Cistinct edges e and eD are called m#ltiple edges if they connect the same end points i.e., if e?=#,v> and eD?=#,v> +ulti:raph; ' graph containing m#ltiple edges. $oop) 'n edge is a loop if it has identical endpoints, i.e. if e?=#,#>
Bepresentation of Nraph
(sin: an adKacency ,atri (sin: an adKacency list
1 2 + ,
1 2 + ,
1 2
2 1 2 x x
, ,
x x
+ ,
, 2
1 2
2 , 2
x x x x + 1 x
+ ,
Operations on Nraphs
Creatin: an e,pty :raph; -o create an empty graph, the entire adJacency list is set to "%$$. 5oid creatgraph6graphnode 7adJ=>, int n#m8 9 int i< for6i?1<iW?n#m<i;;8 adJ=i>?"%$$< @ 5oid creatweightedgraph6graphnode1 7adJ=>, int n#m8 9 int i< for6i?1<iW?n#m<i;;8 adJ=i>?"%$$< @
/nterin: Nraph infor,ation; -he graph information is entered as shownH 5oid inp#tgraph6graphnode 7adJ=>, int n#m8 9 graphnode 7ptr,7last< int I,J,m,val< for6i?1<iW?n#m<i;;8 9 last?"%$$< printf6FGno. of nodes in the adJacency list of node PdI,i8< scanf6FPdI,Ym8< for6J?1<JW?m<J;;8 9 printf6Fenter nodePd)I,J8< scanf6FPdI,Yval8< ptr?6graphnode78malloc6siAeof6graphnode88< ptr/:vertex?val< ptr/:next?"%$$< if6adJ=i>??"%$$8 adJ=i>?last?ptr< else 9 last/:next?ptr< last?ptr< @ @ @ @
Operations on Nraphs
Outputtin: a Nraph; 5oid printgraph6graphnode 7adJ=>,int n#m8 9 graphnode 7ptr< int I< for6i?1<iW?n#m<i;;8 9 ptr?adJ=i>< printf6FPdI,i8< while6ptrZ?"%$$8 9 printf6F/:PdI,ptr/:vertex8< ptr?ptr/:next< @ printf6FGnI8< @ @
Operations on Nraphs
Outputtin: a Nraph; 5oid printweightedgraph6graphnode1 7adJ=>, int n#m8 9 graphnode1 7ptr< int I< for6i?1<iW?n#m<i;;8 9 ptr?adJ=i>< printf6FPdI,i8< while6ptrZ?"%$$8 9 printf6F/:Pd,PdI,ptr/:vertex,ptr/:weight8< ptr?ptr/:next< @ printf6FGnI8< @ @
Operations on Nraphs
Deletin: a Nraph; 5oid deletegraph6graphnode 7adJ=>, int n8 9 int I< graphnaode 7temp,7ptr< for6i?1<iW?n<i;;8 9 ptr?adJ=i>< while6ptrZ?"%$$8 9 temp?ptr< ptr?ptr/:next< free6temp8< @ adJ=i>?"%$$< @ @
Operations on Nraphs
Deletin: a Nraph; 5oid deleteweightedgraph6graphnode1 7adJ=>, int n8 9 int I< graphnaode1 7temp,7ptr< for6i?1<iW?n<i;;8 9 ptr?adJ=i>< while6ptrZ?"%$$8 9 temp?ptr< ptr?ptr/:next< free6temp8< @ adJ=i>?"%$$< @ @
Tra=ersal
Lany applications of the graphs reV#ires examining the vertices and edges of a graph U. there are two standard ways for graph traversal) 9readth first search Depth first search
Oxample
(ndirected Nraph
1 2
+ 1 2
2 , , 2 2
x + 0 , 0 x x x x x
+ , 0
1 + ,
'lgorithm
Step 1)InitialiAe all nodes to ready state 6stat#s ?18 Step 2) &#t the starting node in V#e#e and change its stat#s to the waiting state 6stat#s?28 Step ) 3epeat step + and , #ntil V#e#e is empty Step +) 3emove the front node n of V#e#e. &rocess n and change the stat#s of n to the processed state 6stat#s? 8 Step ,) 'dd to the rear of the V#e#e all the neigh(or of n that are in ready state 6stat#s?18, and change their stat#s to the waiting state 6stat#s?28 =end of the step loop> Step 0) exit
4FS
Step 1) Initially add 2 to the V#e#e
F?0 3?0 F 2 3
Step 2)remove the front element 2 from V#e#e (y setting front?front ;1 add to the V#e#e the neigh(ors of 2
F?1 3?+ F 2 1 , + 3
4FS
Step )3emove the front element 1 from V#e#e (y setting front?front ;1 add to the V#e#e the neigh(ors of 1
F?2 3?+ F 2 1 , + 3
Step +)3emove the front element , from V#e#e (y setting front?front ;1 add to the V#e#e the neigh(ors of ,
F? 3?, F 2 1 , + 0 3
4FS
Step ,) +)3emove the front element + from V#e#e (y setting front?front ;1 add to the V#e#e the neigh(ors of +
F?+ 3?, F 2 1 , + 0 3
Step 0)3emove the front element 0 from V#e#e (y setting front?front ;1 add to the V#e#e the neigh(ors of 0
F?, 3?, F 2 1 , + 0 3
'lgorithm
Step 1)InitialiAe all nodes to ready state 6stat#s ?18 Step 2) &#sh the starting node in stack and change its stat#s to the waiting state 6stat#s?28 Step ) 3epeat step + and , #ntil stack is empty Step +) pop the top node n of stack. &rocess n and change the stat#s of n to the processed state 6stat#s? 8 Step ,) &#sh on to stack all the neigh(or of n that are in ready state 6stat#s?18, and change their stat#s to the waiting state 6stat#s?28 =end of the step loop> Step 0) exit
CFS
Step1) Initially, p#sh on to the stack as follows) stack) Step2) pop and print the top element and p#sh onto the stack all the neigh(ors of 6 those are in the ready state8 as follows) print) stack) 2, ,, 0 Step ) pop and print the top element 0 and p#sh onto the stack all the neigh(ors of 0 6 those are in the ready state8 as follows) print)0 stack) 2, ,
CFS
Step+) pop and print the top element , and p#sh onto the stack all the neigh(ors of , 6 those are in the ready state8 as follows) print), stack) 2,+ Step,) pop and print the top element + and p#sh onto the stack all the neigh(ors of + 6 those are in the ready state8 as follows) print)+ stack) 2, 1
CFS
Step0) pop and print the top element 1 and p#sh onto the stack all the neigh(ors of 1 6 those are in the ready state8 as follows) print)1 stack) 2 Step1) pop and print the top element 2 and p#sh onto the stack all the neigh(ors of 2 6 those are in the ready state8 as follows) print)2 stack) "ow the seV#ence is ,0,,,+,1,2
STUDENT T S?S"
1. Write a menu driven "rogram to im"lement following o"erations on gra"h: i. .reation of a gra"h using ad<acenc$ list+ad<acenc$ 5atri7 ii. !ddition and deletion of a nodes iii. 4raversing 1. CF= 2. /F= A