题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { ListNode * l1=pHead1; ListNode * l2=pHead2; ListNode h=(ListNode(-1)); ListNode * head=&h; ListNode * cur =head; //2 ptr,get the smaller node,and move it to the next, for(;l1!=nullptr&&l2!=nullptr;){ if(l1->val>l2->val){ cur->next=l2; l2=l2->next; }else{ cur->next=l1; l1=l1->next; } cur=cur->next; } if(l1==nullptr) cur->next=l2; else cur->next=l1; l1=head->next; //free(head); it is stored in stack return l1; } };
一开始想着l2拼到l1
其实双指针一个个抽出来会更清晰些