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

要定义两个链表

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

/**
 * 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;
    }
};
原文地址:https://www.cnblogs.com/y1040511302/p/10787617.html