标签:
注意是sorted,两个以排序好的。主要区分情况就能做完
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL) {
return l2;
}
if(l2 == NULL) {
return l1;
}
ListNode* p1;
ListNode* p2;
if(l1->val > l2->val) {
p1 = l1;
p2 = l2;
}
else {
p1 = l2;
p2 = l1;
}
ListNode* head = p2;
while(p2->next != NULL) {
//不存在p2是尾结点
if(p1->val > p2->next->val) {
p2 = p2->next;
continue;
}
else {
if(p1->next == NULL) {
p1->next = p2->next;
p2->next = p1;
return head;
}
ListNode* q = p1;
p1 = p1->next;
q->next = p2->next;
p2->next = q;
continue;
}
}
//如果p2是尾结点
p2->next = p1;
return head;
}
};
标签:
原文地址:http://www.cnblogs.com/xdlyy/p/5357184.html