输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路:分别用两个指针指向两个链表,依次比较两个指针的值。
建议:为了确定结果链表的第一个节点,最好新建一个节点作为头节点,最后的返回是这个新建节点的下一个节点。
/*
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* p1 = pHead1, *p2 = pHead2, *head = new ListNode(-1);
ListNode* p = head;
while(p1 && p2) {
if (p1->val < p2->val){
p->next = p1;
p = p->next;
p1 = p1->next;
} else {
p->next = p2;
p = p->next;
p2 = p2->next;
}
}
while(p1){
p->next = p1;
p = p->next;
p1 = p1->next;
}
while(p2) {
p->next = p2;
p = p->next;
p2 = p2->next;
}
ListNode* res = head->next;
delete head;
return res;
}
};