[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;}
*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】Merge Two Sorted Lists (2 lists)
- leetcode: (21) Merge Two Sorted Lists
- leetcode:Merge Two Sorted Lists
- [leetcode:python]21.Merge Two Sorted Lists
- LeetCode---(21)Merge Two Sorted Lists
- LeetCode——Merge Two Sorted Lists
- [Leetcode] Merge Two Sorted Lists
- Merge Two Sorted Lists leetcode java
- [LeetCode]21 Merge Two Sorted Lists
- LeetCode021 Merge Two Sorted Lists
- LeetCode Merge Two Sorted Lists
- (leetcode)Merge Two Sorted Lists
- LeetCode之Merge Two Sorted Lists
- [C++]LeetCode 21: Merge Two Sorted Lists(合并链表)
- 【LeetCode】Merge Two Sorted Lists和Add TwoNumber解题报告
- LeetCode(21)题解:Merge Two Sorted Lists
- LeetCode----Merge Two Sorted Lists
- leetcode-21-Merge Two Sorted Lists
- Leetcode Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists(合并两个有序单链表)