描述
将两个排序链表合并为一个新的排序链表
您在真实的面试中是否遇到过这个题? 是
样例
给出 1->3->8->11->15->null
,2->null
, 返回 1->2->3->8->11->15->null
。
与合并两组排序数组的思路相同。
/**
* 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) {
// write your code here
if(!l1&&!l2)
return NULL;
if(!l1&&l2)
return l2;
if(!l2&&l1)
return l1;
ListNode *tmp,*ret=NULL;
while(l1&&l2){
ListNode *v;
if(l2->val>l1->val){
v=l1;
l1=l1->next;
}else{
v=l2;
l2=l2->next;
}
v->next=NULL;
if(!ret)
ret=v;
else
tmp->next=v;
tmp=v;
}
if(l1)
tmp->next=l1;
if(l2)
tmp->next=l2;
return ret;
}
};