#include <iostream>
using namespace std;
class List {
public:
List(int num) {
this->num = num;
next = NULL;
}
int num;
List* next;
};
//创建链表
void createList(List* &list) {
List* cur;
int input;
cout<<"输入链表的元素值,以-9999结束"<<endl;
cin>>input;
list = new List(input);
cur = list;
cin>>input;
while(input != -9999) {
cur->next = new List(input);
cur = cur->next;
cin>>input;
}
}
//遍历
void travelList(List* list) {
List* cur = list;
while(cur != NULL) {
cout<<cur->num<<endl;
cur = cur->next;
}
}
//逆置
List* reverseList(List* list) {
List* pre = NULL;
List* cur = list;
List* temp;
while(cur != NULL) {
temp = cur;
cur = cur->next;
temp->next = pre;
pre = temp;
}
return pre;
}
List* merge(List* list1,List* list2){
List* l1 = list1;
List* l2 = reverseList(list2);
List* ret;
if(l1->num < l2->num) {
ret = l1;
l1 = l1->next;
}
List* list = ret;
while(l1 && l2) {
if(l1->num < l2->num) {
list->next = l1;
l1 = l1->next;
} else {
list->next = l2;
l2 = l2->next;
}
list=list->next;
}
if(!l1)
list->next = l2;
else if(!l2)
list->next = l1;
return ret;
}
int main(){
List *l1,*l2;
createList(l1);
createList(l2);
List* ret = merge(l1,l2);
travelList(ret);
return 0;
}
两个链表一升一降,合并为一个升序链表。
最新推荐文章于 2022-09-05 12:37:23 发布