您的位置:首页 > 其它

[LeetCode] Merge Two Sorted Lists

2014-11-27 17:22 387 查看
//题目描述:Merge two sorted linked lists and return it as a new list. The new list should be made by splicing //together the nodes of the first two lists.思路:创建一个新的链表,将l1,l2中元素按由小到大依次插入。wrong的原因是,最初在最后返回的是curr,后来看了网上的许多题解。才知道应该返回headstruct ListNode { int val; ListNode
*next; ListNode(int x) : val(x), next(NULL) {}};ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if(l1==NULL) return l2; if(l2==NULL) return l1; ListNode *p1=l1; ListNode *p2=l2; ListNode *head=NULL; ListNode *curr=NULL; while(p1&&p2){ if(head==NULL){
if(p1->valval){ head=curr=p1; p1=p1->next; curr->next=NULL; } else{ head=curr=p2; p2=p2->next; curr->next=NULL; } } else{ if(p1->valval){ curr->next=p1; curr=p1; p1=p1->next; curr->next=NULL; } else{ curr->next=p2; curr=p2; p2=p2->next; curr->next=NULL; }
} } if(p1){ curr->next=p1; } else if(p2){ curr->next=p2; } return head;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode