文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
/**
* 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* ptrFirst = l1;
ListNode* ptrSecond = l2;
ListNode* head = new ListNode(0);
ListNode* current = head;
while(ptrFirst && ptrSecond) {
if(ptrFirst->val > ptrSecond->val) {
current->next = ptrSecond;
ptrSecond = ptrSecond->next;
}
else {
current->next = ptrFirst;
ptrFirst = ptrFirst->next;
}
current = current->next;
}
if(ptrFirst) {
current->next = ptrFirst;
}
if(ptrSecond) {
current->next = ptrSecond;
}
return head->next;
}
};