谭浩强课后习题9.10 合并两个链表并按升序排列

谭浩强第9章结构体第10题

题目要求:

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

输入样式:

01 A
03 C
26 Z
-1 END
02 B
04 D
05 F
-1 END

输出样式

[1]A->[2]B->[3]C->[4]D->[5]F->[26]Z

代码

/*
	学号,姓名。 把a,b两个链表合并按学号升序排列 
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node{
	int	stdnum;			//学号 
	char name[40];		//姓名 
	struct node *next;	//链表结点 
}SLNode; //定义链表结构体 

SLNode *readlist();
void printflist(SLNode *p);
SLNode *mergesort(SLNode *a,SLNode *b);

int main()
{
	SLNode *a,*b,*c;
	a=readlist();
	//printflist(a);
	
	b=readlist();
	//printflist(b);
	
	c=mergesort(a,b);
	printflist(c);		
}

SLNode *readlist() //键入学生信息,输入-1 end结束
{
	char s[40];
	int n;
	SLNode *head=NULL,*p,*end;
	end=head;
	scanf("%d %s",&n,s);
	while(n!=-1)
	{
		p=(SLNode*)malloc(sizeof(SLNode)); //申请结点空间 
		p->stdnum=n;		//输入学号 
		strcpy(p->name,s);		//输入姓名 
		p->next=NULL;
		//指针操作
		if(head==NULL)
			head=p;
		else
			end->next=p;		
		end=p;	
		scanf("%d %s",&n,s);
	}
	return head;	
} 

void printflist(SLNode *p)
{
	if(p!=NULL)
	{
		printf("[%d]%s",p->stdnum,p->name);
		p=p->next;	
	}
	while(p!=NULL)
	{
		printf("->[%d]%s",p->stdnum,p->name);
		p=p->next;	
	}
	printf("\n");	
} 

SLNode *mergesort(SLNode *a,SLNode *b)
{
	char s[40];
	int temp;
	SLNode *end,*move,*save; 
	//先合并
	//1.指向a链表的指针end移动到末尾 
	end=a;
	save=a; //先保存a链表的首地址
	while(end->next!=NULL)
		end=end->next; //此时指空end移动到最后一个节点 
	//2.链接b链表 
	end->next=b;
				
	//再排序
	move=save; //move用来移动指针 
	end=save;  //end用来作为保存要比较的数 
	while(end)
	{
		move=end;
		while(move)
		{
			if(end->stdnum>move->stdnum)
			{
				temp=end->stdnum;
				end->stdnum=move->stdnum;
				move->stdnum=temp;
				
				strcpy(s,end->name);
				strcpy(end->name,move->name);
				strcpy(move->name,s);	
			}
			move=move->next;	
		}
		end=end->next; 
	} 
	
	return a;
}
发布了137 篇原创文章 · 获赞 8 · 访问量 4332

猜你喜欢

转载自blog.csdn.net/qq_35891520/article/details/105211470