题目描述
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入: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;
}