题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路比较简单,主要是对指针的操作要考虑完全。
/* 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 && !pHead2) return NULL; if (!pHead1) return pHead2; if (!pHead2) return pHead1; ListNode* re, *result; // re不断更新来向尾部创建节点,result存储头指针 if (pHead1->val > pHead2->val) { re = new ListNode(pHead2->val); pHead2 = pHead2->next; } else { re = new ListNode(pHead1->val); pHead1 = pHead1->next; } result = re; while (pHead1 || pHead2) { if (pHead1 && pHead2) { if ((pHead1->val) > (pHead2->val)) { re->next = new ListNode(pHead2->val); pHead2 = pHead2->next; } else { re->next = new ListNode(pHead1->val); pHead1 = pHead1->next; } re = re->next; } else if (pHead1) { while (pHead1) { re->next = new ListNode(pHead1->val); pHead1 = pHead1->next; if (pHead1) re = re->next; } } else { while (pHead2) { re->next = new ListNode(pHead2->val); pHead2 = pHead2->next; if (pHead2) re = re->next; } } } return result; } };