sdut 链表6-------7-6 sdut-C语言实验-有序链表的归并

7-6 sdut-C语言实验-有序链表的归并

分数 20

全屏浏览

切换布局

作者 马新娟

单位 山东理工大学

分别输入两个有序的整数序列(分别包含M和N个数据),建立两个有序的单链表,将这两个有序单链表合并成为一个大的有序单链表,并依次输出合并后的单链表数据。

输入格式:

第一行输入M与N的值;

第二行依次输入M个有序的整数;

第三行依次输入N个有序的整数。

输出格式:

输出合并后的单链表所包含的M+N个有序的整数。

输入样例:

复制代码
6 5
1 23 26 45 66 99
14 21 28 50 100

输出样例:

复制代码
1 14 21 23 26 28 45 50 66 99 100

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

栈限制

8192 KB

cpp 复制代码
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct node pnode;
struct node{
	int data;
	struct node* next;
};
void put(struct node*L)
{
	L = L->next;
	int x=0;
	for(;L!=NULL;L=L->next)
	{
		x++;
		if(x>1) cout<<" ";
		cout<<L->data;
	}
		cout<<endl;
}
void together(struct node*&L1,struct node*&L2)
{
	struct node* p1 = L1->next,*p2 = L2->next,*tail = L1;
	while(p1&&p2)
	{
        //此处也存在思维点,这样子比思维(两个节点比较,小的接前面,大的接后面,每一轮都这样)方便太多了,省时好用!
		if(p1->data<=p2->data)     
		{
			tail->next = p1;                
			p1 = p1->next;                  //tail = p1;
			tail->next->next = NULL;        //p1 = p1->next;
			tail = tail->next;              //tail->next = NULL;
		}
		else 
		{
			tail->next = p2;
			p2 = p2->next;                  //tail = p2;  
			tail->next->next = NULL;        //p2 = p2->next;
			tail = tail->next;              //tail->next = NULL;  
		}
	}
	if(p1!=NULL)
		tail->next = p1;        //这样子会使剩余的所有节点都会接上,简洁好用
	if(p2!=NULL)
		tail->next = p2; 
}
int main()
{
	int m,n;
	while(cin>>m>>n)
	{
    struct node* L1,*p1,*tail1;
	L1 = (pnode*)malloc(sizeof(pnode));
	L1->next = NULL;
	tail1 = L1;
	struct node* L2,*p2,*tail2;
	L2 = (pnode*)malloc(sizeof(pnode));
	L2->next = NULL;
	tail2 = L2;
	int x;
	for(int i=0;i<m;i++)
	{
		cin>>x;
		p1 = (pnode*)malloc(sizeof(pnode));
		p1->next = NULL;
		p1->data = x;
		
		tail1->next = p1;
		tail1 = tail1->next;
	}
	for(int i=0;i<n;i++)
	{
		cin>>x;
		p2 = (pnode*)malloc(sizeof(pnode));
		p2->next = NULL;
		p2->data = x;
		
		tail2->next = p2;
		tail2 = tail2->next;
	}
	together(L1,L2);
	put(L1);
	}
}
相关推荐
程序员zgh2 小时前
Linux系统常用命令集合
linux·运维·服务器·c语言·开发语言·c++
Bigan(安)3 小时前
【奶茶Beta专项】【LVGL9.4源码分析】09-core-obj_class对象类系统
linux·c语言·mcu·arm·unix
qq_433554543 小时前
C++数位DP
c++·算法·图论
AshinGau3 小时前
Softmax 与 交叉熵损失
神经网络·算法
似水এ᭄往昔3 小时前
【C++】--AVL树的认识和实现
开发语言·数据结构·c++·算法·stl
程序员zgh3 小时前
常用通信协议介绍(CAN、RS232、RS485、IIC、SPI、TCP/IP)
c语言·网络·c++
栀秋6663 小时前
“无重复字符的最长子串”:从O(n²)哈希优化到滑动窗口封神,再到DP降维打击!
前端·javascript·算法
xhxxx3 小时前
不用 Set,只用两个布尔值:如何用标志位将矩阵置零的空间复杂度压到 O(1)
javascript·算法·面试
有意义3 小时前
斐波那契数列:从递归到优化的完整指南
javascript·算法·面试
charlie1145141914 小时前
编写INI Parser 测试完整指南 - 从零开始
开发语言·c++·笔记·学习·算法·单元测试·测试