算法總結之 合並兩個有序的單鏈表


  給定兩個有序單鏈表的頭節點head1 和 head2 ,請合並兩個有序鏈表,合並后的鏈表依然有序,並返回合並后鏈表的頭節點

 

假設兩個鏈表長度為M和N 直接給出時間復雜度為(M+N) 額外空間復雜度O(1)

1 如果兩個鏈表中一個為空  則無需合並 返回另一個的鏈表頭節點

2 比較head1 和 head2 的值,小的是合並鏈表的頭節點,記為head   在之后的步驟里 哪個鏈表的頭節點值更小,另一個鏈表的所有節點都會一次插入到這個鏈表中

3不妨設head節點所在的鏈表1, 另一個鏈表2,1和2都從頭部開始一起遍歷,比較每次遍歷的兩個節點的值,記為 cur1 和 cur2  然后根據大小關系做出不同的調整 同時用一個變量pre表示上次比較時值較小的節點

如果兩個鏈表有一個結束,就進入下一步

如果鏈表1先走完,此時cur1=null, pre為鏈表1的最后一個節點,那么就把pre的next指針指向鏈表2的當前的節點cur2。

返回合並后鏈表的頭節點head

 

代碼:

package TT;

public class Test114 {

	public class Node{
		public int value;
		public Node next;
		
		public Node(int data){
			this.value=data;
		}
		
	}
	
	public Node merge(Node head1, Node head2){
		if(head1==null || head2==null){
			  return head1 != null ? head1 : head2;
		}
		Node head = head1.value < head2.value ? head1 : head2;
		Node cur1 = head==head1 ? head1 : head2;
		Node cur2 = head==head1? head2: head1;
		Node pre = null;
		Node next =null;
		
		while(cur1 != null && cur2 != null){
			if(cur1.value <= cur2.value){
				pre=cur1;
				cur1=cur1.next;
			}else {
				next=cur2.next;
				pre.next=cur2;
				cur2.next=cur1;
				pre=cur2;
				cur2=next;
			}
		}
		pre.next=cur1==null ? cur2 : cur1;
		return head;
		
	}
	
	
	
}

  

 


免責聲明!

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



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