CEG's Linux User Group

  • Increase font size
  • Default font size
  • Decrease font size
Home Labs Intersection of Two lists

Intersection of Two lists

E-mail Print
User Rating: / 4
PoorBest 
Article Index
Intersection of Two lists
Source code
Documentation
Test cases and compatibility
All Pages
INTERSECTION OF TWO LISTS


INTRODUCTION:

The objective of the 'Intersection of two list' is to find the common elements in two lists taken into consideration.  It is to be noted that this code works fine for only SORTED LISTS.  Incase if unsorted lists are taken into consideration,  we need to call the sort() function inorder to sort the lists and then find the common elements in the lists.

In the source code, 'temp1' and 'temp2' are pointers that are used to traverse the list  L1 and L2 respectively.  These two temporary variables point to the first element of the lists initially.

Initially first element of the List L1 is compared with the first element of the  List L2.  If the former is smaller, only List L1  is traversed , or if the latter is smaller , only List L2 is traversed.  If there is any element in common, then that element is inserted into another new list called 'm' and in this case both the lists are traversed together .  It is to be noted that in any of the above cases , the lists can be traversed using 'while' loop only if temp1 and temp2 don't point to NULL.

inter1

The first elements of the two lists are compared, since 12<36, List L1 is traversed using temp1.  Now 20 is compared with 36. Since 20<36 , again List L1 is traversed.

inter2
Now 36 of L1 is compared with 36 of L2.  Since they are equal, the intersecting element 36 is stored in the new list 'm'.  And the pointers temp1 and temp2 are traversed.  Now temp1 points to NULL and hence the control come out of the 'while' loop.

inter3

inter4



Last Updated on Tuesday, 09 June 2009 20:49  
Please register or login to add your comments to this article.