CEG's Linux User Group

  • Increase font size
  • Default font size
  • Decrease font size
Home Labs Union of Lists

Union of Lists

E-mail Print
User Rating: / 5
PoorBest 
Article Index
Union of Lists
Source Code
Documentation
Test cases & Compatibility
All Pages

UNION OF LISTS

Introduction :

The objective of this program is to find the union of two lists. The union of the lists includes all the elements of both the lists, but the elements common to the lists are inserted only once. Consider two lists of 2 nodes each. Let l1 and l2 pointers point to the first nodes of list1 and list2 respectively. Let m be the list containing the union of lists. The lists l1 and l2 are displayed below.

 

unionlist1

If temp1->info is less than temp2->info, then temp1->info is inserted in the list m using insertend() function. Then, temp1 is made to point the next node. Else if temp2->info is less then temp1->info, then temp2->info is inserted in the list m using insertend() function. Then, temp2 is made to point the next node. Else if temp1->info and temp2->info are equal, then temp1->info is inserted into the list m. Then, both temp1 and temp2 are made to point their corresponding next node. The above 3 steps are executed repeatedly till if either temp1 and temp2 reaches NULL. If temp1 didn't point NULL, the remaining elements of list 1 are inserted into list m using insertend(). This process is done till temp1 reaches NULL. If temp2 didn't point NULL, the remaining elements of list 2 are inserted into list m using insertend(). This process is done till temp2 reaches NULL.

In this example, 1 is less than 2, so 1 is inserted in list m and temp1 is made to point to node2 of first list.

unionlist4

Now, second node of first list and first node of second list are compared. Since both are equal, 2 is inserted in list m and temp1 and temp2 are made to point NULL and 3 respectively.

unionlist2

Since temp1 reaches NULL, the remaining elements of list 2 are inserted in list m. Thus, the list m is

unionlistm



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