原理很简单,直接上代码吧(Leetcode 21)

/**
 * 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 *head = new ListNode(0), *p = head;
        while(l1 && l2)
        {
            if(l1->val < l2->val)
            {
                p->next = l1;
                l1 = l1->next;
            }
            else
            {
                p->next = l2;
                l2 = l2->next;
            }
            p = p->next;
        }
        if(l1)
            p->next = l1;
        else
            p->next = l2;
        head = head->next;
        return head;
    }
};

 

相关文章:

猜你喜欢
  • 2021-06-23
  • 2021-12-19
  • 2022-12-23
  • 2021-10-11
相关资源
相似解决方案