单链表

//单链表
 
struct studentData{
char sno[4];  /*学号*/
char sname[21];  /*姓名*/
int age;  /*年龄*/
int score[5]; /*五门成绩*/
};
struct student
{ /*数据域*/
struct studentData info;
struct student *next;/*指针域*/
};
//单链表插入

s
truct student *head=NULL,*last=NULL;
//定义链尾指针,始终指向最后一个结点
int AppendOneStudent(struct studentData info){
struct student *newStudent =(struct student *)malloc(siezof(struct student ));
if(newStudent != NULL){
newStudent->info = info; //确定数据域
newStudent->next = NULL; //确定指针域      null改为head就变成创建循环链表
if(head == NULL)  head = newStudent;   //直接插入到表头
else last->next = newStudent;
last = newStudent; //更新last,使其始终指向最后一个结点
return 1;
}
return 0;

 
 //获得单链表的长度
int GetLength()
{
struct student *temp=head;
int len=0;
while(temp!=NULL)
{
len++;
temp=temp->next;
}
return len;
}
//也可以定义一个全局变量,每增加一个结点就加1
 
  //打印链表
void PrintAllStudent(){
struct student *temp=head;
int count = 0;
if(head == NULL){
printf(“nothing”);return;}
while(temp != NULL){
printf(“%d:%s,%s,%d,%d,%d,%d,%d,%d/n”,count++,
temp->info.sno,temp->info.sname, temp->info.age,
temp->info.score[0], temp->info.score[1], temp->info.score[2],
temp->info.score[3], temp->info.score[4]);
temp = temp->next;
}
}
  //学号按升序排序
void OrderBySnoAsc(){  /* 以学号按升序排序 */
struct student *p,*q,*min;
struct studentData temp;   /* 交换时用到的临时变量 */
for( p = head;p != NULL; p = p->next ){
min = p;
for( q = p->next;q != NULL;q = q->next)
if(strcmp( min->info.sno, q->info.sno ) > 0)
min = q;
if( min != p ){
temp=min->info; 
min->info =p->info; p->info=temp;
}
}
}
 
 
//查找节点 
str uct student *SearchStudent(char key[],struct Student **preNode){
struct student *temp;
if(head == NULL){
return NULL;
}
*preNode = temp = head;
while(temp != NULL){
if(strcmp(temp->info.sno,key) == 0) break;
*preNode = temp; /* 向下移动时,保存当前结点的地址 */
temp = temp->next;
}
return temp;

 

/ /删除前面找到的节点

b ool DeleteOneStudent(char key[]){  //该函数删除第index个结点
struct student *preNode,*delNode;
delNode=SearchStudent(key,&preNode);
if(delNode!= NULL){
if(delNode==head)
{ head=head->next; //删除头结点}
else { preNode ->next=delNode->next;}
delete delNode;  //释放节点空间
return true;
}
else return false;
} /* 问题:是否需要考虑删除尾结点的情况? */ 
 
//删除整个链表

void DeleteAll(){
struct Student *temp = head,preNode = head;
while(temp != NULL){
preNode = temp;
temp = temp->next;
delete preNode;
}
head = NULL;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值