思路:
這道題不需要集合放入兩個(gè)鏈表再進(jìn)行重排序,只需要兩個(gè)指針,按大小進(jìn)行遍歷,代碼如下:文章來源:http://www.zghlxwxcb.cn/news/detail-850841.html
class Solution {
/**
* 1->3->5->7
* 2->4->6->8->10->12
*
* 1->3->5->7
* h c1
* p
* 2->4->6->8->10->12
* c2
*
* 每次都是比較c1和c2 那個(gè)小 誰小p的next指針指向誰
* 然后c1 或者c2 向前走一位,p來到p.next 位置
*
* 最后判斷p.next=c1==null?c2:c1
*/
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1==null||list2==null){
return list1==null?list2:list1;
}
ListNode head=list1.val<=list2.val?list1:list2;
ListNode cur1=head.next;
ListNode cur2=head==list1?list2:list1;
ListNode pre=head;
while (cur1!=null&&cur2!=null){
if (cur1.val<=cur2.val){
pre.next=cur1;
cur1=cur1.next;
}else {
pre.next=cur2;
cur2=cur2.next;
}
pre=pre.next;
}
pre.next=cur1==null?cur2:cur1;
return head;
}
}
?文章來源地址http://www.zghlxwxcb.cn/news/detail-850841.html
到了這里,關(guān)于27、鏈表-合并兩個(gè)有序鏈表的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!