struct student *SortInsert (struct student *head,struct student *node)
{
struct student *p; //p保存当前需要检查的节点的地址
struct student *t; //临时指针变量
if (head == NULL) //处理空的有序链表
{
head = node;
node->next = NULL;
n += 1; //插入完毕,节点总数加
return head;
}
p = head; //有序链表不为空
while(p->num < node->num && p != NULL) //p指向的节点的学号比插入节点的学号小,并且它不等于NULL
{
t = p; //保存当前节点的前驱,以便后面判断后处理
p = p->next; //后移一个节点
}
if (p == head) //刚好插入第一个节点之前
{
node->next = p;
head = node;
}
else //插入其它节点之后
{
t->next = node; //把node节点加进去
node->next = p;
}
n += 1; //插入完毕,节点总数加1
return head;
}
综上所述,链表的各类操作函数的完整代码如下:
#include "stdlib.h"
#include "stdio.h"
#define NULL 0
#define LEN sizeof(struct student)
struct student
{
int num; //学号
float score; //分数,其他信息可以继续在下面增加字段
struct student *next; //指向下一节点的指针
};
int n; //节点总数
/*
==========================
功能:创建n个节点的链表
返回:指向链表表头的指针
==========================
*/
struct student *Create()
{
struct student *head; //头节点
struct student *p1 = NULL; //p1保存创建的新节点的地址
struct student *p2 = NULL; //p2保存原链表最后一个节点的地址
n = 0; //创建前链表的节点总数为0:空链表
p1 = (struct student *) malloc (LEN); //开辟一个新节点
p2 = p1; //如果节点开辟成功,则p2先把它的指针保存下来以备后用
if(p1==NULL) //节点开辟不成功
{
printf ("nCann't create it,否则就变成"野指针",即地址不确定的指针
return head; //返回创建链表的头指针
}
/*
===========================
功能:输出节点
返回: void
===========================
*/
void Print(struct student *head)
{
struct student *p;
printf ("nNow,p->next);
p = p->next; //移到下一个节点
}
while (p != NULL);
}
}
(编辑:晋中站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|