LeetCode 合并两个有序链表

题目描述

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

分析

可以采用新建一个链表的形式,并且从头开始不断比较两个链表中存储值的大小,并将较小的存储到新链表的节点中,然后指针向后移动,重新对两个节点的值进行比较,不断选取较小的加入到其中。直至两个链表全部移动到空指针完毕。


#include "pch.h"
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}	
};
ListNode* CreateList();
void Showlist(ListNode* l);
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2);
int main() {
	ListNode* l1 = CreateList();
	ListNode* l2 = CreateList();
	Showlist(l1);
	Showlist(l2);
	ListNode* l3 = mergeTwoLists(l1, l2);
	Showlist(l3);
	return 0;
}
void Showlist(ListNode* l) {
	for (ListNode* l1 = l; l1 != nullptr; l1 = l1->next) {
		cout << l1->val;
		if (l1->next != nullptr)
			cout << "-->";
	}
	cout << endl;
}
ListNode* CreateList() {
	ListNode* head = new ListNode(0);
	head->next = nullptr;
	ListNode* curr = head;
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		curr->next = new ListNode(0);
		cin >> curr->next->val;
		curr = curr->next;
	}
	return head->next;
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
	ListNode* head = new ListNode(0);
	ListNode* curr = head;
	while (l1!=nullptr&&l2!=nullptr)
	{
		curr->next = new ListNode(0);
		if (l1->val >= l2->val) {
			curr->next->val = l2->val;
			l2 = l2->next;
		}
		else
		{
			curr->next->val = l1->val;
			l1 = l1->next;
		}
		curr = curr->next;
	}
	if(l1==nullptr)
		for (l2; l2 != nullptr; l2 = l2->next) {
			curr->next = new ListNode(0);
			curr->next->val = l2->val;
			curr = curr->next;
		}
	else if (l2 == nullptr)
		for (l1; l1 != nullptr; l1 = l1->next) {
			curr->next = new ListNode(0);
			curr->next->val = l1->val;
			curr = curr->next;
		}
	return head->next;
}

递归合并

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
	if (l1 == nullptr) {
		return l2;
	}
	else if (l2 == nullptr) {
		return l1;
	}
	else if (l1->val >= l2->val) {
		l2->next = mergeTwoLists(l1, l2->next);
		return l2;
	}
	else
	{
		l1->next = mergeTwoLists(l1->next, l2);
		return l1;
	}
}

不创建新的链表:节约空间效率较高

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
	ListNode* prehead = new ListNode(0);
	ListNode* curr = prehead;
	while (l1!=nullptr&&l2!=nullptr)
	{
		if (l1->val <= l2->val) {
			curr->next = l1;
			l1 = l1->next;
		}
		else
		{
			curr->next=l2;
			l2 = l2->next;
		}
		curr = curr->next;//使指针指向当前节点
	}
	if (l1 != nullptr) {  //连接剩余部分
		curr->next = l1;
	}
	else if (l2 != nullptr) {
		curr->next = l2;
	}
	return prehead->next;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值