107 lines
2.2 KiB
C
107 lines
2.2 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
// 定义学生信息的数据结构,链表的节点
|
|
typedef struct stu_s
|
|
{
|
|
char sid;
|
|
char name[32];
|
|
int age;
|
|
|
|
struct stu_s *next;
|
|
} STU;
|
|
|
|
void shows(STU *head)
|
|
{
|
|
STU *pi = head;
|
|
printf("学号\t姓名\t年龄\n");
|
|
|
|
while (NULL != pi)
|
|
{
|
|
printf("%d\t%s\t%d\n", pi->sid, pi->name, pi->age);
|
|
pi = pi->next;
|
|
}
|
|
}
|
|
|
|
STU *insert_head(STU *head, STU new_stu)
|
|
{
|
|
// 动态创建新节点
|
|
STU *new_node = (STU *)malloc(sizeof(STU));
|
|
*new_node = new_stu;
|
|
|
|
// 实现头部插入
|
|
if (NULL == head) // 如果是第一个节点(空链表)
|
|
{
|
|
head = new_node;
|
|
}
|
|
else
|
|
{
|
|
// 头结点变第二个节点,新节点变头结点
|
|
new_node->next = head; // 新节点指向头节点
|
|
head = new_node; // 头指针指向新节点
|
|
}
|
|
|
|
return head; // 返回头节点,头指针不能改变
|
|
}
|
|
|
|
STU *insert_end(STU *head, STU *item)
|
|
{
|
|
// 实现尾部插入
|
|
if (NULL == head) // 如果是第一个节点(空链表)
|
|
{
|
|
head = item;
|
|
}
|
|
else
|
|
{
|
|
STU *pi = head;
|
|
while (NULL != pi->next)
|
|
{
|
|
pi = pi->next;
|
|
}
|
|
pi->next = item;
|
|
}
|
|
|
|
return head; // 返回头节点,头指针不能改变
|
|
}
|
|
|
|
STU *insert_sort(STU *head, STU *item)
|
|
{
|
|
if (NULL == head)
|
|
return item;
|
|
|
|
if (head->age > item->age)
|
|
{
|
|
item->next = head;
|
|
head = item;
|
|
}
|
|
else
|
|
{
|
|
STU *pi = head;
|
|
while (NULL != pi->next && pi->next->age < item->age)
|
|
{
|
|
pi = pi->next;
|
|
}
|
|
item->next = pi->next;
|
|
pi->next = item;
|
|
}
|
|
|
|
return head;
|
|
}
|
|
|
|
int main()
|
|
{
|
|
// 静态生成学生信息的链表
|
|
STU s1 = {1, "张三", 18, NULL}; // 头节点: 参数说明: 学号, 姓名, 年龄, 下一个节点的地址
|
|
STU s2 = {2, "李四", 19, NULL};
|
|
STU s3 = {3, "王五", 20, NULL};
|
|
|
|
STU *head = NULL; // 头节点
|
|
head = insert_sort(head, &s1);
|
|
head = insert_sort(head, &s2);
|
|
head = insert_sort(head, &s3);
|
|
head = insert_sort(head, &(STU){4, "赵六", 17, NULL});
|
|
|
|
shows(head);
|
|
|
|
return 0;
|
|
} |