java:合並兩個排序的鏈表(遞歸+非遞歸)


//采用不帶頭結點的鏈表  非遞歸實現
public static ListNode merge(ListNode list1,ListNode list2){
	if(list1==null)
		return list2;
	else if(list2==null)
		return list1;
	
	ListNode newHead=null;
	ListNode tmp=null;
	//往新鏈表一個個添加節點 直至有一個鏈表為空
	//tmp存放最后一個添加進新鏈表的節點 用於后續的拼接
	while(list1!=null&&list2!=null){
		if(list1.value<list2.value){
			if(newHead==null){
				newHead=tmp=list1;
			}else{
				tmp.next=list1;
				tmp=tmp.next;
			}
			list1=list1.next;
		}else{
			if(newHead==null){
				newHead=tmp=list2;
			}else{
				tmp.next=list2;
				tmp=tmp.next;
			}
			list2=list2.next;
		}
	}
	//拼接剩余鏈表至新鏈表尾節點
	if(list1==null){
		tmp.next=list2;
	}else{
		tmp.next=list1;
	}
	return newHead;	
}

//遞歸實現
public static ListNode mergeRecur(ListNode list1,ListNode list2){
	if(list1==null)
		return list2;
	if(list2==null)
		return list1;
	
	ListNode newHead=null;
	if(list1.value<=list2.value){
		newHead=list1;
		newHead.next=mergeRecur(list1.next, list2);
	}else{
		newHead=list2;
		newHead.next=mergeRecur(list1, list2.next);
	}
	return newHead;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM