合并两个排序链表
/**
* 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
ListNode *Tl1=l1,*Tl2=l2;
ListNode *T=new ListNode(0),*tmp=NULL;//首先这里必须得new一个分配一个地址
tmp=T;
while(Tl1&&Tl2)
{
if(Tl1->val>=Tl2->val)
{
tmp->next=new ListNode(0);
tmp=tmp->next;
tmp->val=Tl2->val;
Tl2=Tl2->next;
}
else
{
tmp->next=new ListNode(0);
tmp=tmp->next;
tmp->val=Tl1->val;
Tl1=Tl1->next;
}
}
if(Tl1)//直接把剩下链表的指针拿来
tmp->next=Tl1;
if(Tl2)
tmp->next=Tl2;
return T->next;
}
};
合并两个排序链表
Accepted
总耗时:
144 ms
100% 数据通过测试.