Question
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
Solution
- 合并思想和归并排序的Merge过程差不多,但是这是操作链表,每个链表都需要用到两个辅助指针来完成操作,一共四个指针。
Code
/*
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* pH1, *pre1, *pH2, *pre2;
pH1 = pHead1;
pH2 = pHead2;
while (pH1 && pH2) {
if (pH1->val > pH2->val) {
pre2 = pH2;
pH2 = pH2->next;
pre2->next = pH1;
pre1 = pH1;
pH1 = pH1->next;
pre1->next = pH2;
} {
pre1 = pH1;
pH1 = pH1->next;
pre1->next = pH2;
pre2 = pH2;
pH2 = pH2->next;
pre2->next = pH1;
}
}
return pHead1;
}
};