/**
* 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) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
ListNode* head = new ListNode(-1);
ListNode* cnt = head;
while(l1 != NULL && l2 != NULL){
if(l1->val <= l2->val){
cnt->next = l1;
l1 = l1->next;
}
else{
cnt->next = l2;
l2 = l2->next;
}
cnt = cnt->next;
}
cnt->next = l1 ? l1 : l2;
return head->next;
}
};
思路很简单,注意的是指针中当前到底指的是哪一个
比如最开始创建了一个head,是用来指向最开头的那个cnt,因为cnt后面会不断更新