题解

合并两个排序的链表

http://www.nowcoder.com/questionTerminal/d8b6b4358f774294a89de2a6ac4d9337

public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        ListNode h = new ListNode(-1);
        ListNode cur = h;
        while(list1 != null && list2 !=null){
            if(list1.val<=list2.val){
                cur.next = list1;
                list1 = list1.next;
            }else{
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        if(list1!=null) cur.next = list1;
        if(list2!=null) cur.next = list2;
        return h.next;
    }
}

全部评论
最后if(list1 != null)应该用while语句吧,不能确定还剩下几个元素
6 回复 分享
发布于 2020-01-09 15:59
最后一个return .next 666
点赞 回复 分享
发布于 2021-09-26 17:16
思路和我一毛一样
点赞 回复 分享
发布于 2020-10-08 14:17
最后的 if(list1!=null) cur.next = list1; if(list2!=null) cur.next = list2;应该是while循环吧?
点赞 回复 分享
发布于 2020-10-06 07:41
为什么最后返回的是h.next不是cur?
点赞 回复 分享
发布于 2020-05-29 23:21
牛逼
点赞 回复 分享
发布于 2020-05-27 17:59
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { ListNode *res = new ListNode(0); ListNode*current = res; if (pHead1 == NULL&&pHead2!=NULL){ return pHead2; }else if (pHead1 != NULL&&pHead2==NULL){ return pHead1; }else if (pHead1 == NULL &&pHead2 == NULL){ return NULL; } else{ while (pHead1!=NULL && pHead2!=NULL) { if (pHead1->val < pHead2->val){ current->next = pHead1; current = current->next; pHead1 = pHead1->next; } else{ current->next = pHead2; current = current->next; pHead2 = pHead2->next; } } if (pHead1 == NULL){ while (pHead2) { current->next = pHead2; current = current->next; pHead2 = pHead2->next; } } if (pHead2 == NULL){ while (pHead1) { current->next = pHead1; current = current->next; pHead1 = pHead1->next; } } } res = res->next; return res; } 和你的代码很像...可惜我写了一坨屎..
点赞 回复 分享
发布于 2019-11-14 22:23

相关推荐

10-16 15:48
算法工程师
点赞 评论 收藏
分享
评论
58
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务