给出 1->3->8->11->15->null,2->null,
返回 1->2->3->8->11->15->null。
感觉很像mergeSort
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// write your code here
if(l1 == nullptr && l2 == nullptr) {
return nullptr;
}
if (l1 == nullptr) {
return l2;
}
if (l2 == nullptr) {
return l1;
}
ListNode *p = new ListNode();
ListNode *head = p;
if (l1->val < l2->val) {
p->val = l1->val;
l1 = l1->next;
}
else {
p->val = l2 ->val;
l2 = l2->next;
}
while (l1 != nullptr && l2 != nullptr) {
if (l1->val <= l2->val) {
ListNode *q = new ListNode (l1->val);
p->next = q;
p = p->next;
l1 = l1->next;
}
else {
ListNode *q = new ListNode (l2->val);
p->next = q;
p = p->next;
l2 = l2->next;
}
}
if (l1 != nullptr) {
p->next = l1;
}
else if (l2 !=nullptr) {
p->next = l2;
}
return head;
}
};
原文:http://blog.csdn.net/susser43/article/details/46584827