两个链表一升一降,合并为一个升序链表。

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值