目录
题目
输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
数据范围: 0 \le n \le 10000≤n≤1000,-1000 \le 节点值 \le 1000−1000≤节点值≤1000
要求:空间复杂度 O(1)O(1),时间复杂度 O(n)O(n)
如输入{1,3,5},{2,4,6}时,合并后的链表为{1,2,3,4,5,6},所以对应的输出为{1,2,3,4,5,6},转换过程如下图所示:
或输入{-1,2,4},{1,3,4}时,合并后的链表为{-1,1,2,3,4,4},所以对应的输出为{-1,1,2,3,4,4},转换过程如下图所示:
代码
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* Create(int n)
{
Node* p, * h, * s;
h = new Node;
h->next = NULL;
p = h;
for (int i = 0; i < n; i++)
{
s = new Node;
cin >> s->data;
p->next = s;
p = s;
}
p->next = NULL;
return h;
}
void Print(Node* h)
{
Node* p = h->next;
while (p != NULL)
{
cout << p->data << "\t";
p = p->next;
}
cout << endl;
}
vector<int>Merge_singly_linked_lists(Node* head1, Node* head2)
{
vector<int> ans;
Node* p1 = head1->next;
while (p1 != NULL)
{
ans.push_back(p1->data);
p1 = p1->next;
}
Node* p2 = head2->next;
while (p2 != NULL)
{
ans.push_back(p2->data);
p2 = p2->next;
}
sort(ans.begin(), ans.end());
for (vector<int>::iterator it = ans.begin(); it != ans.end(); it++)
{
cout << *it << "\t";
}
cout << endl;
return ans;
}
int main()
{
Node* head1 = new Node;
head1->next = NULL;
Node* head2 = new Node;
head2->next = NULL;
int i;
cout << "请输入第一个单链表的结点个数:";
cin >> i;
cout << "请输入第一个升序单链表:";
head1 = Create(i);
int j;
cout << "请输入第二个单链表的结点个数:";
cin >> j;
cout << "请输入第二个升序单链表:";
head2 = Create(j);
cout << "两个升序单链表合并之后依旧是升序单链表,其结点值为:";
Merge_singly_linked_lists(head1, head2);
return 0;
}