题解 | #合并两个排序的链表#
合并两个排序的链表
http://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 *p1,*p2,*pre; p1=pHead1,p2=pHead2,pre=pHead1; while(p1!=NULL&&p2!=NULL) { if(p2->val<=p1->val) { if(p1==pHead1) { ListNode *temp=p2->next; p2->next=p1; pHead1=p2; p2=temp; pre=pHead1; } else { ListNode *temp=p2->next; p2->next=p1; pre->next=p2; p2=temp; pre=pre->next; } } else { if(p1==pHead1) { p1=p1->next; } else { p1=p1->next; pre=pre->next; } } } if(p2==NULL) return pHead1; else { pre->next=p2; return pHead1; } } };