package com.my.util;
/** * 單向鍊錶節點
* */
public
class
singlenode
}
package com.my.suanfa;
import com.my.util.singlenode;
/** * 合併兩個有序的單鏈表
* 如果鍊錶1的長度為m,鍊錶2的長度為n,
* 則時間複雜度為o(m+n),空間複雜度為o(1)
* */
public
class
solution16
//定義有限幾個變數記錄特殊位置
//兩個鍊錶的頭結點較小的為新鍊錶的頭結點
singlenode head = head1.value < head2.value ? head1 : head2;
//cur1記錄包含新的頭結點的鍊錶
singlenode cur1 = head == head1 ? head1 : head2;
//cur2記錄另一條鍊錶
singlenode cur2 = head == head1 ? head2 : head1;
singlenode pre = null;
//記錄不包含頭結點的鍊錶的未排序部分
singlenode next = null;
while
(cur1 != null && cur2 != null)
else
}//退出迴圈後一定有一條鍊錶已經遍歷完了,即cur1 == null || cur2 == null
//將沒有遍歷完的鍊錶的剩餘部分全部連線到新鍊錶的後面
pre.next = cur1 != null ? cur1 : cur2;
//返回新的頭結點
return head;
}}
合併兩個有序單鏈表
include using namespace std typedef struct nodenode,linklist void creatlist linklist l void insert int n,node p void show linklist l cout num head2 ne...
合併兩個有序單鏈表
思路 第一種 遞迴法 這個方法不好想,遞過去的時候做的事情是找到新的單鏈表的下乙個節點,歸的時候做的是告訴每個節點的next是什麼繫結關係,帶入資料就能知道怎麼回事 public listnode merge listnode a,listnode b if b null listnode newh...
合併兩個有序單鏈表
題目 給定兩個有序單鏈表的頭節點head1和head2,請合併兩個有序鍊錶,合併後的鍊錶依然有序,並返回合併後的鍊錶的頭節點。例如 0 2 3 7 null 1 3 5 7 9 null 合併後的鍊錶為 0 1 2 3 3 5 7 7 9 null 本題考察鍊錶基本操作 關鍵是能寫出時間複雜度o m...