Bootstrap

C++10.2链表

C++练习:链表

题目要求

建立一个10名学生信息的单向链表,
每个结点包括学号、姓名、性别、年龄,
采用插入排序按学号对其从小到大排列。

PS:我用的是visual studio 2019,所以不用加一些头文件

代码部分

#include<iostream>
using namespace std;

int main() {
	//建立一个10名学生信息的单向链表,每个结点包括学号、姓名、性别、年龄,采用插入排序按学号对其从小到大排列。
	struct student
	{
		int sno;
		char name[20];
		char sex[3];
		int age;
		struct student* next;
	}stu1, stu2, stu3, stu4, stu5, stu6, stu7, stu8, stu9, stu10;
	stu1 = { 5 ,"s05" ,"男" ,18 };
	stu2 = { 3 ,"s03","男", 18 };
	stu3 = { 2 ,"s02", "男", 18 };
	stu4 = { 4,"s04","男", 18 };
	stu5 = { 6,"s06", "男", 18 };
	stu6 = { 1 ,"s01" ,"男", 18 };
	stu7 = { 8 ,"s08" ,"男", 19 };
	stu8 = { 9, "s09", "男", 18 };
	stu9 = { 10, "s10", "男", 18 };
	stu10 = { 7 ,"s07" ,"男", 18 };
	struct student* s[10] = { &stu1,&stu2,&stu3,&stu4,&stu5,&stu6,&stu7,&stu8,&stu9,&stu10 };
	struct student* head = s[0];
	struct student* stu;
	struct student* sture = NULL;
	head->next = NULL;
	for (int i = 1; i < 10; i++) {

		stu = head;

		while (s[i]->sno > stu->sno && stu->next != NULL) {

			sture = stu;
			stu = stu->next;
		}
		if (s[i]->sno <= stu->sno) {
			if (stu == head) {
				head = s[i];
				head->next = stu;
			}
			else {
				sture->next = s[i];
				s[i]->next = stu;
			}

		}
		else
		{
			stu->next = s[i];
			s[i]->next = NULL;
		}

	}
	stu = head;
	cout << "*****************排序结果*****************" << endl;
	cout << "学号" << "\t" << "姓名" << "\t" << "性别" << "\t" << "年龄" << "\t" << endl;
	for (int n = 0; n < 10; n++) {
		cout << stu->sno<<"\t" << stu->name << "\t" << stu->sex << "\t" << stu->age << "\t" << endl;
		stu = stu->next;
	}
	return 0;
}

结果
在这里插入图片描述

;