问题 z: C语言程序设计教程(第三版)课后习题11.8

题目描述:
已有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

解题思路:
尾插法建立a、b两个链表后,先用冒泡排序对两个链表根据结构体中的成员id进行升序排序;然后再进行合并操作。

c参考代码(带头结点):

#include <stdio.h>
#include <stdlib.h>

int n,m;

typedef struct Node{
    
    
	int id;
	int grade;
	struct Node *next;
}N,*node;

node create(int n)
{
    
    
    node head;
    head=(node)malloc(sizeof(N));
    head->next=NULL;
    
	node rear;
	node s;
	rear=head;
	
	int i,t1,t2;
	for(i=0;i<n;i++)
	{
    
    
		s=(node)malloc(sizeof(N));
		scanf("%d%d",&s->id,&s->grade);
		s->next=NULL;
		
	    rear->next=s;
		rear=s;	

	}
	
	return head;
}

//void Bubblesort(node p1,node p2)
//{
    
    
//	int i,j,temp1,temp2;
//	node p;
//	
//	for(i=0;i<n-1;i++)
//	{
    
    
//		for(p=p1->next;p->next!=NULL;p=p->next)
//		{
    
    
//			if(p->id>p->next->id)
//			{
    
    
//				temp1=p->id;
//				p->id=p->next->id;
//				p->next->id=temp1; 
//			
//			    temp2=p->grade;
//				p->grade=p->next->grade;
//				p->next->grade=temp2; 
//			}
//		} 
//	}
//	
//	for(j=0;j<m-1;j++)
//	{
    
    
//		for(p=p2->next;p->next!=NULL;p=p->next)
//		{
    
    
//			if(p->id>p->next->id)
//			{
    
    
//				temp1=p->id;
//				p->id=p->next->id;
//				p->next->id=temp1;
//				
//				temp2=p->grade;
//				p->grade=p->next->grade;
//				p->next->grade=temp2; 
//			}
//		}
//	}
//}

void sort(node p1,node p2)
{
    
    
	int temp1,temp2;
	node A;
	node B;
	for(A=p1->next;A!=NULL;A=A->next)
	{
    
    
		for(B=A->next;B!=NULL;B=B->next)
		{
    
    
			if(A->id>B->id)
			{
    
    
				temp1=A->id;
				A->id=B->id;
				B->id=temp1;
				
				temp2=A->grade;
				A->grade=B->grade;
				B->grade=temp2;
			}
		}
	}
	
	for(A=p2->next;A!=NULL;A=A->next)
	{
    
    
		for(B=A->next;B!=NULL;B=B->next)
		{
    
    
			if(A->id>B->id)
			{
    
    
				temp1=A->id;
				A->id=B->id;
				B->id=temp1;
				
				temp2=A->grade;
				A->grade=B->grade;
				B->grade=temp2;
			}
		}
	}
}

node link(node P1,node P2)
{
    
    
	node head=(node)malloc(sizeof(N));
	node p=head;
	node p1=P1->next;
	node p2=P2->next;
	
	while(p1!=NULL&&p2!=NULL)
	{
    
    
		if(p1->id<p2->id)
		{
    
    
			p->next=p1;
			p=p1;
			p1=p1->next;
		}
		else
		{
    
    
			p->next=p2;
			p=p2;
		    p2=p2->next;
		}
	}
	if(p1!=NULL)
	 p->next=p1;
	else
	 p->next=p2;
	 
	return head;
}

void print(node p)
{
    
    
   while(p->next!=NULL)
   {
    
    
   	printf("%d %d\n",p->next->id,p->next->grade);
   	p=p->next;
   }
}

int main()
{
    
    
	scanf("%d%d",&n,&m);
	node a,b,c;

	a=create(n);
	b=create(m);
	
	sort(a,b);
	c=link(a,b);
	print(c);
	return 0;
}

参考资料:
传送门

猜你喜欢

转载自blog.csdn.net/qq_46139801/article/details/114694099