C语言链表练习(2)

版权声明:CSDN_那木桑 https://blog.csdn.net/qq_43897345/article/details/89790340

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

  • 建立链表
  • 以链表a为基础,像升序插入结点一样,将链表b中的每个结点学号进行比较,再插入
  • 注意过程中的特殊位置(开头,链表结尾)
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
typedef struct student{
	int num;
	int score;
	struct student *next;
}Stu;

Stu lista,listb;
int n=0,sum=0;

int main()
{
	Stu *insert(Stu *ah,Stu *bh);
	void print(Stu *head);
	Stu *creat ();
	Stu *ahead, *bhead, *abh;
	printf("input list a:");
	ahead=creat();
	sum=sum+n;
	printf("input list b:");
	bhead=creat();
	sum=sum+n;
	abh=insert(ahead,bhead);
	print(abh);
	return 0;
}

//建立链表函数
Stu *creat ()
{
	Stu *head, *p1, *p2;
	head=NULL;
	n=0;
	p1=p2=(Stu *)malloc(LEN);
	printf("input number&score of student:\n");
	printf("if number is 0,stop inputing.\n");
	scanf("%d,%d",&p1->num,&p1->score);
	while(p1->num!=0){
		n=n+1;
		if(n==1) head=p1;
		else p2->next=p1;
		p2=p1;
		p1=(Stu *)malloc(LEN);
		scanf("%d,%d",&p1->num,&p1->score);
	}
	p2->next=NULL;
	return head;
}

//定义一个函数,用来合并两个链表
Stu *insert(Stu *ah,Stu *bh)
{
	Stu *pa1, *pa2, *pb1, *pb2;
	pa1=pa2=ah;
	pb1=pb2=bh;
	do{
		while((pb1->num>pa1->num)&&(pa1->next!=NULL)){
			pa2=pa1;
			pa1=pa1->next;
		}
		if(pb1->num<=pa1->num){
			if(ah==pa1) ah=pb1;
			else pa2->next=pb1;
			pb1=pb1->next;
			pb2->next=pa1;
			pa2=pb2;
			pb2=pb1;
		}
	}while((pa1->next!=NULL)||(pa1==NULL&&pb1!=NULL));
	if((pb1!=NULL)&&(pb1->num>pa1->num)&&(pa1->next==NULL))
		pa1->next=pb1;
	return ah;
}


void print(Stu *head)
{
	Stu *p;
	printf("There are %d records:\n",sum);
	p=head;
	if(p!=NULL)
		do{
			printf("%d %d\n",p->num,p->score);
			p=p->next;
		}while(p!=NULL);
}

猜你喜欢

转载自blog.csdn.net/qq_43897345/article/details/89790340