//题目描述: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] Merge Two Sorted Lists
最新推荐文章于 2024-07-16 23:15:32 发布