题解 | #合并两个排序的链表#
合并两个排序的链表
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) { if(pHead1 == NULL ) return pHead2; if(pHead2 == NULL ) return pHead1; ListNode* newNode = new ListNode(-1); ListNode* curNode =newNode; while(pHead1 != NULL && pHead2 != NULL){ if(pHead1->val <= pHead2->val){ curNode->next = pHead1; pHead1 = pHead1->next; } else{ curNode->next = pHead2; pHead2 = pHead2->next; } curNode = curNode->next; } if(pHead1 != NULL) curNode->next = pHead1; else curNode->next = pHead2; return newNode->next; } };