实例要求如下:
- 建立一个10结点的单向链表;
- 每个结点包括学号、姓名、性别、年龄;
- 采用插入排序法对其排序;
- 按学号从小到大排列;
- 编译器使用Dev-C++;
代码如下:
#include<iostream>
using namespace std;
struct Student
{
int sno;
char name[20];
char sex;
int age;
Student* next;
};
Student stu[10] ={{7, "Smith", 'M', 18},
{8, "Kerry", 'F', 19},
{9, "Levy", 'M', 16},
{4, "Doris", 'F', 20},
{5, "Ella", 'F', 18},
{6, "Carrie", 'M', 22},
{1, "Barbara", 'F', 23},
{10, "Carmen", 'M', 20},
{2, "Brice", 'M', 19},
{3, "Auden", 'M', 20}};
int main() {
//建立一个10名学生信息的单向链表,每个结点包括学号、姓名、性别、年龄,采用插入排序按学号对其从小到大排列。
Student* s[10] = { &stu[0],&stu[1],&stu[2],&stu[3],&stu[4],&stu[5],&stu[6],&stu[7],&stu[8],&stu[9]};
Student* head = s[0];
Student* k;
Student* sture = NULL;
head->next = NULL;
for (int i = 1; i < 10; i++) {
k = head;
while (s[i]->sno > k->sno && k->next != NULL) {
sture = k;
k = k->next;
}
if (s[i]->sno <= k->sno) {
if (k == head) {
head = s[i];
head->next = k;
}
else {
sture->next = s[i];
s[i]->next = k;
}
}
else
{
k->next = s[i];
s[i]->next = NULL;
}
}
k = head;
cout << "*****************排序结果*****************" << endl;
cout << "学号" << "\t" << "姓名" << "\t" << "性别" << "\t" << "年龄" << "\t" << endl;
for (int n = 0; n < 10; n++) {
cout << k->sno<<"\t" << k->name << "\t" << k->sex << "\t" << k->age << "\t" << endl;
k= k->next;
}
return 0;
}
运行结果如下: