算法總結之 合並兩個有序的單鏈表
阿新 • • 發佈:2017-09-11
插入 一個 大小 spa 下一步 則無 算法總結 做出 頭節點
給定兩個有序單鏈表的頭節點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; } }
算法總結之 合並兩個有序的單鏈表