首页 > 编程语言 > 详细

LeetCode 21. Merge Two Sorted Lists(c++)

时间:2019-04-28 23:16:45      阅读:154      评论:0      收藏:0      [点我收藏+]

要定义两个链表

判断时依次对应每一个链表的值进行判断即可。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
         ListNode* h;
        ListNode* l3=new ListNode(0);       //注意
        h=l3;                                           //注意
        while(l1!=NULL&&l2!=NULL){
            if(l1->val<l2->val){
                h->next=l1;
                l1=l1->next;
            }
            else{
                h->next=l2;
                l2=l2->next;
            }
            h=h->next;
        }
        if(l1!=NULL){
            h->next=l1;
        }
        if(l2!=NULL){
            h->next=l2;
        }
        return l3->next;
    }
};

 

LeetCode 21. Merge Two Sorted Lists(c++)

原文:https://www.cnblogs.com/y1040511302/p/10787617.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!