一、迴圈實現
#include using namespace std;
struct listnode
};class solution
if (phead2 == null)
//判斷合併煉表頭節點是從哪個節點開始
if (phead1->val <= phead2->val)
else
listnode *prehead = null, *nexthead = null;
while (phead1 != null && phead2 != null)
prehead->next = phead2;//鍊錶1遍歷的上乙個節點後繼鍊錶2當前節點(插入節點開始)
nexthead = phead2->next;//臨時儲存鍊錶2當前節點的下乙個節點
phead2->next = phead1;//鍊錶2當前節點後繼鍊錶1當前節點(插入節點完成)
phead1 = prehead->next;//鍊錶1當前節點退回到剛插入進去的節點
phead2 = nexthead;//鍊錶2當前節點後移
}else
prehead->next = phead1;
nexthead = phead1->next;
phead1->next = phead2;
phead2 = prehead->next;
phead1 = nexthead;
}} return head;
}};int main(void)
二、遞迴實現
#include using namespace std;
struct listnode
};class solution
if (phead2 == null)
/*拿情況phead1->val <= phead2->val為例進行說明:
merge(phead1->next, phead2)返回的肯定是已經排好序的鍊錶(假設是x),
由於當前phead1->val <= phead2->val,所以只有phead1能拿到後繼x的資格
*/if (phead1->val <= phead2->val)
else
}};int main(void)
合併兩個有序遞增的鍊錶,使得合併後新鍊錶還是有序的
合併兩個有序遞增的單鏈表,使得合併後,新鍊錶也是遞增有序的。這裡分別使用迴圈 遞迴實現合併有序鍊錶 迴圈實現鍊錶合併和遞迴實現鍊錶的合併如下所示 package cn.edu.nwu.structs.linklist author jcm 時間 2016年8月22日 public class mer...
鍊錶 將兩個遞增鍊錶合併為乙個遞減鍊錶
王道p38t13 主 linklist merge desc linklist a,linklist b else t next c next c next t if ap null r ap else r bp while r null return c 完整 include include us...
兩公升序鍊錶合併
問題 輸入兩個非遞減序列的序列,合併這兩個鍊錶並使新鍊錶中的結點仍然是按照非遞減排序的,要求使用原來的鍊錶空間。例如 1,3,9 和 2,8 結果為 1,2,3,8,9 分析 分析完畢,看 include includetypedef int datatype typedef struct node...