题意
给定两个有序链表,要求合并成一个有序链表
分析
采用归并排序中使用的双指针归并的方法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2) {
if(l1 ==NULL || l2 == NULL){
return l1==NULL?l2:l1;
}
ListNode* dummy = new ListNode(-1);
ListNode* p = dummy;
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;
if(l2)p->next = l2;
return dummy->next;
}
};