# leetcode-Merge Two Sorted Lists-21

/**
* 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) {
ListNode* tail;
ListNode* p=l1;
ListNode* q=l2;
if(p==NULL) return l2;
if(q==NULL) return l1;

if(p->val <= q->val){
p=p->next;
tail->next=NULL;
}
else{
q=q->next;
tail->next=NULL;
}
while(p&&q){
if(p->val <= q->val){
tail->next=p;
tail=p;
p=p->next;
tail->next=NULL;
}
else{
tail->next=q;
tail=q;
q=q->next;
tail->next=NULL;
}
}
if(p) tail->next=p;
else tail->next=q;
}
};

/**
* 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) {
ListNode* tail;
ListNode* p=l1;
ListNode* q=l2;
if(p==NULL) return l2;
if(q==NULL) return l1;

if(p->val <= q->val){
ListNode* tmp;   //用一个临时的指针来赋值
tmp->val=p->val;<span style="white-space:pre">	</span>//猜想是不是指针不能这么用！！！！
tmp->next=NULL;
p=p->next;
delete tmp;
}
else{
ListNode* tmp;
tmp->val=q->val;  //同理
tmp->next=NULL;
q=q->next;
delete tmp;
}
while(q&&p){
if(p->val <= q->val){
ListNode* tmp;<span style="white-space:pre">	</span>//同理
tmp->val=p->val;
tmp->next=NULL;
tail->next=tmp;
tail=tmp;
p=p->next;
delete tmp;
}
else{
ListNode* tmp;   //同理
tmp->val=q->val;
tmp->next=NULL;
tail->next=tmp;
tail=tmp;
q=q->next;
delete tmp;
}
}
if(p) tail->next=p;
else tail->next=q;
}
};

#### Merge k Sorted Lists -- LeetCode

2014-02-25 09:45:41

#### leetcode-Merge Two Sorted Lists

2013-12-17 19:27:03

#### Leetcode-Merge Two Sorted Lists-Python

2017-08-21 19:29:46

#### 两个有序数组的中位数Median of Two Sorted Arrays（很重要）

2016-06-21 11:11:03

#### leetcode之 median of two sorted arrays

2013-09-10 00:15:50

#### Merge Two Sorted Lists -- LeetCode

2014-02-22 23:31:00

#### 【leetcode c++】21 Merge Two Sorted Lists

2015-06-18 13:37:28

#### LeetCode(40) Median of Two Sorted Arrays (两排序数组中位数)

2015-09-22 21:18:45

#### 《LeetBook》leetcode题解(4): Median of Two Sorted Arrays[H]——两个有序数组中值问题

2016-04-09 21:24:06

#### Leetcode-Merge Two Sorted Lists

2014-10-14 11:20:39