题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
Solution1:
如果一个为空,则返回另一个。当两个都不为空时,比较大小选择小的那个加入新建的链表中,直到一方为空。
最后将不为空的链表加到新建链表的尾部。
Solution2:
递归解法
Solution1:
/* 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)return pHead2; if (!pHead2)return pHead1; ListNode *p, *q, *head = nullptr; while (pHead1&&pHead2){ if (pHead1->val < pHead2->val){ p = pHead1; pHead1 = pHead1->next; } else{ p = pHead2; pHead2 = pHead2->next; } if (head == nullptr){ head = q = p; } else{ q->next = p; q = p; } } if (pHead1)p->next = pHead1; if (pHead2)p->next = pHead2; return head; } };Solution2:
/* 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; if(pHead1->val<pHead2->val){ pHead1->next=Merge(pHead1->next,pHead2); return pHead1; }else{ pHead2->next=Merge(pHead1,pHead2->next); return pHead2; } } };
本文介绍了一种算法,用于合并两个已排序的链表,使之成为一个新的有序链表。提供了两种解决方案,一种是非递归方法,另一种是递归方法。这两种方法都能确保合并后的链表保持递增顺序。

631

被折叠的 条评论
为什么被折叠?



