题解 | #合并两个排序的链表#
合并两个排序的链表
http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
尾插法
新建前置头指针vhead,尾指针cur并初始化为vhead。若两链表均为遍历完,则把值小的尾插到vhead中。当其中一个链表遍历完后,就把另一个链表链接到vhead后面。
C++代码:
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
ListNode *vhead = new ListNode(-1), *cur = vhead;
while (pHead1 && pHead2) {
if (pHead1->val < pHead2->val) {
cur->next = pHead1;
pHead1 = pHead1->next;
} else {
cur->next = pHead2;
pHead2 = pHead2->next;
}
cur = cur->next;
}
cur->next = pHead1 == NULL ? pHead2 : pHead1;
return vhead->next;
}
};