合并两个有序链表(递归和非递归方法C++)

利用递归和非递归方法合并两个有序链表:

注意点:
1、代码中以输入的方式生成两个链表,在生成完毕第一个链表之后要将cin的内容清空。不然会引起第二个链表无法输入生成的问题。

#include<iostream>
#include<vector>

using  namespace std;

struct Node {
	int val;
	Node* next;
	Node(int num):val(num),next(nullptr){}
};

Node* CreatList() {
	Node* head = new Node(0);
	Node* ptr = head;
	cout << "Please input a number(q to quit): ";
	int temp;
	while (cin >> temp) {
		Node* newNode = new Node(temp);
		newNode->next = ptr->next;
		ptr->next = newNode;
		ptr = newNode;
		cout << "Please input a number(q to quit): ";
	}
	while (getchar() != '\n');
	cin.clear();
	return head->next;
}

Node* MerageList(Node* list1, Node* list2) {
	if (list1 == nullptr || list2 == nullptr)
		return list1 == nullptr ? list2 : list1;
	Node* head = new Node(0), *ptr = head;
	while (list1 != nullptr&&list2 != nullptr) {
		if (list1->val < list2->val) {
			ptr->next = list1;
			list1 = list1->next;
			ptr = ptr->next;
		}
		else {
			ptr->next = list2;
			list2 = list2->next;
			ptr = ptr->next;
		}
	}
	if (list1 == nullptr)
		ptr->next = list2;
	else
		ptr->next = list1;
	ptr = head->next;
	delete head;
	return ptr;
}

Node* MerageListRe(Node* list1, Node* list2) {
	Node* head = nullptr;
	if (list1 == nullptr || list2 == nullptr)
		return list1 == nullptr ? list2 : list1;

	if (list1->val < list2->val) {
		head = list1;
		head->next = MerageListRe(list1->next, list2);
	}
	else {
		head = list2;
		head->next = MerageListRe(list1, list2->next);
	}

	return head;
}

void Show(Node* list) {
	while (list) {
		cout << list->val << " ";
		list = list->next;
	}
	cout << endl;
}

int main() {
	Node* head1 = CreatList();
	Show(head1);
	Node* head2 = CreatList();
	Show(head2);
	//Node* merageList = MerageList(head1, head2);
	//Show(merageList);
	Node* merageListRe = MerageListRe(head1, head2);
	Show(merageListRe);
	
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值