+ Reply to Thread
Results 1 to 2 of 2

Thread: Merge two sorted Linked Lists

  1. #1
    TopGun Guest

    Merge two sorted Linked Lists

    Write a program to merge two sorted linked lists. Consider all possible test cases.

  2. #2
    admin's Avatar
    admin is offline Administrator
    Join Date
    Mar 2010
    Posts
    44
    Structure definition:
    Code:
    typedef struct linkedList* List;
    struct linkedList{
    	int num;
    	struct linkedList *next;
    };
    Code:
    List mergeList(List L, List L1)
    {
    	List t1=NULL, t2=NULL, temp=NULL, root=NULL;
    	
    	if(!L && !L1) {
    		cout<<"Both are NULL"<<endl;
    		return NULL;
    	}
    	else if(!L)
    		return L1;
    	else if(!L1) {
    		cout <<"Second is NULL"<<endl;
    		return L;
    	}
    	else {
    		root = (L->num < L1->num)?L:L1;
    		while(L && L1) {
    			if(L->num < L1->num){
    				while(L && (L->num <= L1->num)){
    					t1 = L;
    					L= L->next;
    				}
    				t1->next = L1;
    			}
    			else if(L->num > L1->num){
    				while(L1 && (L->num > L1->num)){
    					t2 = L1;
    					L1 = L1->next;
    				}
    				t2->next = L;
    			}
    			else {
    				t1 = L;
    				temp = L->next;
    				L->next = L1;
    				L = temp;
    			}
    		}
    		return root;
    	}
    	
    }

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Linked List merge
    By TopGun in forum Algorithm/Data Structure Questions
    Replies: 1
    Last Post: 30th May 2008, 15:22
  2. Merge two sorted Linked Lists
    By TopGun in forum Microsoft
    Replies: 1
    Last Post: 30th May 2008, 14:18

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts