合并排好序的两个链表

原理很简单,直接上代码吧(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;
    }
};
原文地址:https://www.cnblogs.com/zhangbaochong/p/5152120.html