合并两个有序链表
2019-12-15 本文已影响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 *dummyHead = new ListNode(0);
ListNode *cur = dummyHead;
while(l1 != NULL && l2 != NULL){
if (l1->val < l2->val){
cur->next = l1;
cur = cur->next;
l1 = l1->next;
}
else{
cur->next = l2;
cur = cur->next;
l2 = l2->next;
}
}
if (l1 == NULL){
cur->next = l2;
}
if (l2 == NULL){
cur->next = l1;
}
return dummyHead->next;
}
};