View Code of Problem 83

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

typedef struct node{
	int num;
	int score;
	struct node *next;
}Node,*LinkList;	//node节点,lisklist链表 

LinkList create(int n){
	LinkList L;
	Node *r,*s;		//r指向末尾,s新建节点 
	int i=0;
	L=(Node*)malloc(sizeof(Node));	//	为什么该处写成 
					// L = (LinkSList)malloc(sizeof(SNode));也可以? 
	r=L;
	for(i=0;i<n;i++){
		s=(Node*)malloc(sizeof(Node));	//	
		scanf("%d %d",&s->num,&s->score);
		r->next=s;	//
		r=s;	
	}
	r->next=NULL;	//返回链表末尾 
	return L;
}

void print_list(LinkList L){
	Node *p;
	p=L->next;
	while(p!=NULL){	//p是L->next, 不要写成p->next
		printf("%d %d\n",p->num,p->score);
		p=p->next;
	}
}

LinkList merge(LinkList a,LinkList b){	//合并两个链表 
	Node *p;
	p=a->next;
	while(p->next!=NULL){	//使 p指向队尾 
		p=p->next;
	}
	p->next=b->next;	// ?b的返回值是队尾? 
	free(b);
	return a;
}

LinkList sort_list(LinkList a){	//从小到大排序 
	Node *p,*q;
	Node *min;		//p指向头结点 
	int num,score;
	p=a->next;
	while(p->next!=NULL){
		min=p;	//
		for(q=p->next;q!=NULL;q=q->next){	//当前往后有更小的吗 
			if(q->num < min->num){
				min=q;
			}
		}
		//后面更小的与p现在指向的交换 
        if(min != p)	//为什么 设置temp 交换不行? 
        {
            num = p->num;
            score = p->score;
            p->num = min->num;
            p->score = min->score;
            min->num = num;
            min->score = score;
        }
		p=p->next;
	}
	return a;
}

int main(){
	LinkList a,b;
	int n,m;
	scanf("%d %d",&n,&m);
	a=create(n);
	b=create(m);
	a=merge(a,b);
	a=sort_list(a);
	print_list(a);
	
	return 0;
} 

Double click to view unformatted code.


Back to problem 83