链表代码求调(红题,简单的链表)
  • 板块学术版
  • 楼主difficultlong
  • 当前回复3
  • 已保存回复4
  • 发布时间2025/2/4 19:22
  • 上次更新2025/2/5 08:24:21
查看原帖
链表代码求调(红题,简单的链表)
1435692
difficultlong楼主2025/2/4 19:22

题目就是合并两个有序数列(从小到大),变为一个新的有序数列
样例

比如:1 3 5
2 3 8

合为:1 2 3 3 5 8

很简单(但是我是蒟蒻),其次要求必须用链表做,所以请不要回复关于“用双指针就可以做”等这样的回答

代码(看着很唬人,实际上多看几眼就清晰了):

#include<bits/stdc++.h>
using namespace std;
struct Node{
	int value;
	Node *next;
}*head1,*head2,linked1[100001],linked2[100001];
//-------------------------------(链表)
int main(){
	head1=NULL,head2=NULL;
	int n,m;
	scanf("%d%d",&n,&m);
	Node *t1;
	for(int i=1;i<=n;i++){
		scanf("%d",&linked1[i].value);
		if(head1==NULL){
			head1=&linked1[i];
			t1=head1;
		}
		else{
			t1=t1->next;
			t1=&linked1[i];
		}
	}
	Node *t2;
	for(int i=1;i<=m;i++){
		scanf("%d",&linked2[i].value);
		if(head2==NULL){
			head2=&linked2[i];
			t2=head2;
		}
		else{
			t2=t2->next;
			t2=&linked2[i];
		}
	}
//上面全是读入↑
	Node linked[200001],*head,*t;
	head=NULL;
	t1=head1,t2=head2;
	for(int i=1;i<=n+m;i++){
		if(((t1->value)<(t2->value))&&t1!=NULL){
			linked[i].value=t1->value;
			t1=t1->next;
		}
		else
			if((t1->value)>=(t2->value)&&t2!=NULL){
			linked[i].value=t2->value;
			t2=t2->next;
		}
		if(head==NULL){
			head=&linked[i];
			t=head;
		}
		else{
			t=t->next;
			t=&linked[i];
		}
	}
	for(Node *a=head;a;a=a->next){
		printf("%d ",a->value);
	}
	return 0;
}

谢谢各位的帮助,回复只要能与我的代码稍微沾边就给关。

2025/2/4 19:22
加载中...