第16题 合并两个排序的链表
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2){
ListNode* n = new ListNode(-1);
ListNode* cur = n;
while(pHead1 && pHead2){
if(pHead1->val<pHead2->val){
cur->next = pHead1;
cur = pHead1;
pHead1 = pHead1->next;
}else{
cur->next = pHead2;
cur = pHead2;
pHead2 = pHead2->next;
}
}
cur->next = pHead1 ? pHead1 : pHead2;
return n->next;
}
};
递归:
/*
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;
if(pHead1->val<pHead2->val){
pHead1->next = Merge(pHead1->next,pHead2);
return pHead1;
}else{
pHead2->next = Merge(pHead1,pHead2->next);
return pHead2;
}
}
};
本文介绍了如何使用递归和迭代方法合并两个单调递增的链表,提供了C++代码示例,并探讨了两种算法的时间复杂性。
6664

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



