#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NAME_MAX 30
typedef struct student_node *S_P;
typedef struct student_node{
int id;
char name[NAME_MAX];
float score;
struct student_node *next;
}S_T;
//创建节点
S_P mk_node(int id, char *name, float score)
{
S_P p = malloc(sizeof(S_T));
if(p != NULL){
p->id = id;
strcpy(p->name,name); //字符串
p->score = score;
p->next = NULL;
}
return p;
}
//从head插入
S_P insert_head(S_P head, int id, char *name, float score)
{
S_P newp = mk_node(id, name, score);
if(!head || !newp){
if(!head){
head = newp;
}
return head;
}
newp->next = head;
head = newp;
return head;
}
//从tail插入
S_P insert_tail(S_P head, int id, char *name, float score)
{
S_P newp = mk_node(id, name, score);
S_P tail;
if(!head || !newp){
if(!head){
head = newp;
}
return head;
}
for(tail = head; tail->next; tail = tail->next)
;
//tail存放是是尾节点
tail->next = newp;
return head;
}
//按升序插入node
S_P insert_sort_node(S_P head, int id, char *name, float score)
{
S_P newp = mk_node(id, name, score);
S_P pre, cur;
//判断head newp node是否创建成功
if(!head || !newp){
if(!head){
head = newp;
}
return head;
}
for(pre = cur = head; cur && cur->score < score;
pre = cur, cur = cur->next)
;
if(cur == head){
newp->next = head;
head = newp;
}else{
newp->next = cur;
pre->next = newp;
}
return head;
}
//打印linklist
void disp_linklist(S_P head)
{
S_P cur;
for(cur = head; cur; cur = cur->next){
printf("%d\t%s\t%.2f\n", cur->id, cur->name, cur->score);
}
}
void delete_linklist(S_P head)
{
S_P cur, next;
#if 1
for(cur = head; cur; cur = next){
next = cur->next;
free(cur);
}
#endif
#if 0
cur = head;
while(cur != NULL){
next = cur->next;
free(cur);
cur = next;
}
#endif
}
S_P delete_node(S_P *headp, float key)
{
S_P del, pre, cur;
//没有head节点的情况
if(*headp == NULL)
return NULL;
//删除的节点恰好是头结点
if( (*headp)->score == key ){
del = *headp;
*headp = (*headp)->next;
del->next = NULL;
return del;
}
for( pre = *headp, cur = (*headp)->next; cur;
pre = pre->next, cur = cur->next){
if(cur->score == key ){
del = cur;
cur = cur->next;
del->next = NULL;
pre->next = cur;
return del;
}
}
return NULL;
}
int main(void)
{
int id;
char name[NAME_MAX];
float score;
S_P head = NULL, del;
while(1){
scanf("%d %s %f", &id, name, &score);
getchar();
if(id == 0 )
break;
//head = insert_sort_node(head, id, name, score);
//要有返回值
// head = insert_head(head, id, name, score);
head = insert_tail(head, id, name,score);
}
printf("---------------\n");
disp_linklist(head);
while( (del = delete_node(&head, 3)) ){
printf("del:%d %s %f\n", del->id, del->name, del->score);
free(del);
}
printf("---------------\n");
disp_linklist(head);
delete_linklist(head);
return 0;
}
/*
akaedu@akaedu-G41MT-D3:~/lin/809$ ./mylinklist
1 adad 88
5 linbo 86
4 adav 3
0 0 0
---------------
1 adad 88.00
5 linbo 86.00
4 adav 3.00
del:4 adav 3.000000
---------------
1 adad 88.00
5 linbo 86.00
*/
mylinklist
最新推荐文章于 2021-01-20 19:21:24 发布