Codeup——607 | 问题 B: C语言-链表排序

题目描述

已有a、b两个链表,每个链表中的结点包括学号、成绩。要求把两个链表合并,按学号升序排列。

输入

第一行,a、b两个链表元素的数量N、M,用空格隔开。 接下来N行是a的数据 然后M行是b的数据 每行数据由学号和成绩两部分组成

输出

按照学号升序排列的数据

样例输入

2 3
5 100
6 89
3 82
4 95
2 10

样例输出

2 10
3 82
4 95
5 100
6 89
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

struct student{
    
    
	int sno;
	int score;
	struct student *next;
};

int main()
{
    
    
	int m,n,i,j;
	struct student *h,*pre,*p;
	cin >>m>>n;
	h=NULL;
	for(i=0;i<m+n;i++){
    
    	//将两个链表接在一起
		p=new student;
		cin >>p->sno>>p->score;
		p->next=NULL;
		if(!h)
			h=p;
		else
			pre->next=p;
		pre=p;
	}
	for(i=0;i<m+n;i++){
    
    	//排序
		p=h;
		for(j=0;j<m+n-1-i;j++){
    
    
			if(p->sno>p->next->sno){
    
    	//交换信息
				int temp1=p->sno;
				p->sno=p->next->sno;
				p->next->sno=temp1;
				int temp2=p->score;
				p->score=p->next->score;
				p->next->score=temp2;
			}
			p=p->next;
		}
	}
	p=h;
	while(p){
    
    	//输出
		printf("%d %d\n",p->sno,p->score);
		p=p->next;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44888152/article/details/107039509