Sorting algorithm for merging two ordered singly linked lists

Sorting algorithm for merging two ordered singly linked lists

analysis

For an ordered unilateral list, first use the first linked list list1 as the benchmark, and compare it with the linked list list2 in a loop.

  • If the first linked list ends first, directly connect the back part of the second linked list after list1.

  • If the second one ends first, there is no need to traverse. End directly.
    In doing so, the time complexity is the length of list1, which is O(n).
    Of course, the time complexity is the fastest if the broken linked list is the quasi-base.

Code

// 合并两个 有序的单链表,让其有序
LinkList MARGELIST(LinkList l1,LinkList l2){   
	 LinkList list ,p,q,r,s;    
	 q=l2;    
	 list =l1;    
	 p=list;    
	 r=p;    
	 while (p!=NULL&&q!=NULL) {   	 		
	 	 if (p->data<q->data){              
	 		 	r=p;              
	 		 	p=p->link;          
	 		 }else{              
	 		 	s=q;              
	 		 	q=q->link;              
	 		 	s->link=p;    
	 		 	// 这里为什么这么写,主要是为了解决list1的第一个结点
                                // 就比list2的第一个结点大的时候              
	 		 	if (r==p) {     
	 		 		r=s;                  
	 		 		list=r;              
	 		 	}else{                 
	 		 		r->link=s;                   
	 		 		r=s;                
	 		 	}          
	 		 }        
	 }    
	 if (q!=NULL){        
	 	r->link=q;    
	 }        
	 return list;
}

Guess you like

Origin blog.csdn.net/honeylife/article/details/100152075