题目链接:https://leetcode.com/problems/merge-two-sorted-lists/
Runtimes:17ms
1、问题
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
2、分析
两个指针p,q分别指向l1,l2,如果p->next->val < q->val,则p往前走,否则插入q当前节点。要注意的一点是p指针一定要在前一个节点才能够执行删除操作。
3、小结
指针要检查是否为空的情况,切记。
4、实现
/**
* 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(NULL == l1 && NULL == l2)
return NULL;
else if(NULL == l1)
return l2;
else if(NULL == l2)
return l1;
ListNode *p, *q, *head;
if(l1->val > l2->val){
head = p = l2;
q = l1;
}else{
head = p = l1;
q = l2;
}
while(p->next != NULL && q != NULL)
{
while(p->next != NULL && p->next->val < q->val)
{
p = p->next;
}
if(p->next == NULL)
break;
ListNode *r = p->next;
p->next = q;
q = q->next;
p->next->next = r;
p = p->next;
}
if(q != NULL)
p->next = q;
return head;
}
};
5、反思
题目简单,效果不错。