http://www.lintcode.com/zh-cn/problem/merge-two-sorted-lists/
合并两个排序链表A,B有很多种方法,其中最简单的就是创建一个空链表C,之后依次将A,B的元素插入C即可。
这次我是直接将B中的元素插入A,不需要额外的链表C
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param l1: ListNode l1 is the head of the linked list
* @param l2: ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode * mergeTwoLists(ListNode * l1, ListNode * l2) {
ListNode *it1 = l1, *it1_pre = nullptr, *it2 = l2, *temp = nullptr;
if(l1 == nullptr){
return l2;
}
while(it1 != nullptr || it2 != nullptr){
if(it1 !=nullptr && it2 != nullptr){
temp = it2->next;
if(it1->val > it2->val){//it2比it1小则插在it1之前
if(it1_pre == nullptr){//it1前一个元素为空
l1 = it2; //即it1为第一个元素
}else{
it1_pre->next = it2;
}
it2->next = it1;
it1_pre = it2;
it2 = temp;
}else{//都不满足则it1往下走
it1_pre = it1;
it1 = it1->next;
}
}else if(it2 != nullptr){//it1已经遍历完成则将l2剩余部分放至l1尾部
it1_pre->next = it2;
return l1;
}else{//l2已经完全插入l1
return l1;
}
}
}
};