1. 程式人生 > >用連結串列儲存學生資訊然後排序輸出

用連結串列儲存學生資訊然後排序輸出

題目:4.建立一個連結串列,每個結點包括:學號,姓名,年齡,性別。要求輸入3個人的資訊,將他們按照年齡正序/逆序排序輸出他們的資訊。 下面是程式碼: 結構體模組:

typedef struct Student{	
	long num;
	char name[8];
	int age;
	char sex[5];
	Student *next;
}stu;

初始化模組

void init(stu **pNode,int n){
	int i = 1;
	while (i<=n){
		stu *node = *pNode;
		stu *temp;
		if (*pNode == NULL){
			*pNode = (stu *)malloc(sizeof(stu));
			long num;
			printf("輸入第%d個學生學號:", i);
			scanf("%ld", &num);
			(*pNode)->num = num;
			char name[10];
			printf("輸入第%d個學生姓名:", i);
			scanf("%s", (*pNode)->name);
			int age;
			printf("輸入第%d個學生年齡:", i);
			scanf("%d", &age);
			(*pNode)->age = age;
			char sex[5];
			printf("輸入第%d個學生性別:", i);
			scanf("%s", (*pNode)->sex);
			(*pNode)->next = NULL;
			i++;
		}
		else{
			node = *pNode;
			while (node->next != NULL){
				node = node->next;
			}
			temp = (stu *)malloc(sizeof(stu));
			long num;
			printf("輸入第%d個學生學號:", i);
			scanf("%ld", &num);
			temp->num = num;
			char name[10];
			printf("輸入第%d個學生姓名:", i);
			scanf("%s", temp->name);
			int age;
			printf("輸入第%d個學生年齡:", i);
			scanf("%d", &age);
			temp->age = age;
			char sex[5];
			printf("輸入第%d個學生性別:", i);
			scanf("%s", temp->sex);
			temp->next = NULL;
			node->next = temp;
			i++;
		}
	}
}

排序模組

stu *paixu(stu *pNode){
	stu *node1 = (stu*)malloc(sizeof(stu));
	stu *node2 = (stu*)malloc(sizeof(stu));
	for (node1 = pNode; node1 != NULL; node1 = node1->next){
		for (node2 = node1->next; node2 != NULL; node2 = node2->next){
			if (node1->num > node2->num){
				stu *temp = (stu*)malloc(sizeof(stu));
				temp->num = node1->num;
				*temp->name = *node1->name;
				temp->age = node1->age;
				*temp->sex = *node1->sex;
				node1->num = node2->num;
				*node1->name = *node2->name;
				node1->age = node2->age;
				*node1->sex = *node2->sex;
				node2->num = temp->num;
				*node2->name = *temp->name;
				node2->age = temp->age;
				*node2->sex = *temp->sex;
			}
		}
	}
	return pNode;
}

遍歷函式

void bianli(stu *pNode){
	stu *node;
	node = pNode;
	printf("學號\t姓名\t年齡\t性別\t\n");
	while(node->next != NULL){
		printf("%ld\t", node->num);
		printf("%s\t", node->name);
		printf("%d\t", node->age);
		printf("%s\t", node->sex);
		printf("\n");
		node = node->next;
	}
	printf("%ld\t", node->num);
	printf("%s\t", node->name);
	printf("%d\t", node->age);
	printf("%s\t", node->sex);
	printf("\n");
}

主函式

int _tmain(int argc, _TCHAR* argv[])
{
	int n;
	printf("請輸入要存入資訊的人數:");
	scanf("%d", &n);
	stu *head = NULL;
	init(&head,n);
	stu *newhead = paixu(head);
	bianli(newhead);
	system("pause");
	return 0;
}

測試結果:(漢字輸入會有一個字亂碼,正在修改) 在這裡插入圖片描述