#include<iostream>
using namespace std;
struct ListNode {
int value;
ListNode* next;
};
ListNode* Merge(ListNode* head1,ListNode* head2){
if (!head1 || !head2) return head1 == NULL ? head2 : head1;
ListNode*p=head1, *q=head2,*h=NULL,*l=NULL,*t=NULL;
while (p&&q){
if (p->value > q->value) {
l = q;
q = q->next;
}
else {
l = p;
p = p->next;
}
if(!h) h = l;
if(!t) t = l;
else {
t->next = l;
t = t->next;
}
}
if (p || q) {
if (!p) t->next = q;
else t->next = p;
}
return h;
}//方法一,非递归
ListNode* Merge2(ListNode* head1, ListNode* head2) {
if (head1 == NULL) return head2;
else if (head2 == NULL) return head1;
ListNode* h = NULL;
if (head1->value < head2->value) {
h = head1;
h->next = Merge(head1->next, head2);
}
else if (head1->value >= head2->value){
h = head2;
h = Merge(head1, head2->next);
}
return h;
}//方法二,递归
int main(){
ListNode *l = new ListNode();
l->value = 1;
l->next = new ListNode();
l->next->value = 2;
l->next->next = new ListNode();
l->next->next->value = 7;
l->next->next->next = new ListNode();
l->next->next->next->value = 8;
ListNode *k = new ListNode();
k->value = 3;
k->next = new ListNode();
k->next->value = 9;
ListNode* p = Merge2(l,k);
cout << p->value << " " << p->next->value << " " << p->next->next->value<<" "<< l->next->next->next->value<<endl;
return 0;
}
剑指offer25
最新推荐文章于 2023-05-30 08:00:00 发布