0
点赞
收藏
分享

微信扫一扫

ACM模式 | 合并两个排序的链表 | AcWing36

狐沐说 2022-03-30 阅读 56
c++

 题目

 

#include<iostream>
#include<vector>
using namespace std;

struct Listnode {
	int val;
	Listnode* next;
	Listnode(int x) :val(x), next(NULL) {}
};

Listnode* createList(vector<int>& nums) {
	if (nums.size() == 0) {
		return NULL;
	}
	Listnode* head = new Listnode(nums[0]);
	Listnode* curnode = head;

	for (int i = 1; i < nums.size(); i++) {
		curnode->next = new Listnode(nums[i]);
		curnode = curnode->next;
	}
	return head;
}

Listnode* merge(Listnode* l1, Listnode* l2) {
	Listnode* dummy = new Listnode(0);
	Listnode* cur = dummy;
	while (l1 != NULL && l2 != NULL) {
		if (l1->val < l2->val)
		{
			cur->next = l1;
			l1 = l1->next;
		}
		else {
			cur->next = l2;
			l2 = l2->next;
		}
		cur = cur->next;
	}
	cur->next = l1 ? l1 : l2;
	return dummy->next;
}

int main() {

	int a;
	vector<int> nums;
	while (cin >> a) {
		nums.push_back(a);
		if (cin.get() == '\n')
			break;
	}
	Listnode* head1 = createList(nums);
	nums.clear();
	while (cin >> a) {
		nums.push_back(a);
		if (cin.get() == '\n')
			break;
	}
	Listnode* head2 = createList(nums);
	Listnode* ans = merge(head1, head2);
	while (ans) {
		cout << ans->val << " ";
		ans = ans->next;
	}
	return 0;
}

 

举报

相关推荐

0 条评论