一、完成单链表操作,要求节点构造类型。
1、建立学生结构体(学号,姓名,成绩)
2、循环调用头插法创建整表
3、遍历单链表
4、任意位置插入一个完整的学生信息
5、任意位置删除一个学生。
6、单链表逆置
7、单链表按照学生成绩排序。
#include <stdio.h>
#include <stdlib.h>//创建学生结构体
typedef struct
{int id;char name[20];float score;
}stu;//创建单链表
typedef struct node
{union {int len;stu data;};struct node* next;
}Link, * Plink;Plink create()
{Plink p = malloc(sizeof(Link));if (p == NULL){printf("申请失败\n");return NULL;}p->len = 0;p->next = NULL;return p;
}//头插法
int front_insert(Plink L, stu e)
{if (L == NULL){printf("头插失败\n");return -1;}Plink p = malloc(sizeof(Link));p->data = e;p->next = L->next;L->next = p;L->len++;return 0;
}//遍历单链表
int output_link(Plink L)
{if (L == NULL || L->len == 0){printf("链表为空\n");return -1;}int i;Plink t = L;for (i = 0; i < L->len; i++){t = t->next;printf("学号:%d\t姓名:%s\t分数:%.2f\n", t->data.id, t->data.name, t->data.score);}printf("\n");return 0;
}//在任意位置插入节点
int anypos_insert(Plink L, int pos, stu e)
{if (pos<1 || pos>L->len + 1 || L == NULL){printf("插入失败\n");return -1;}int i;Plink t = L;for (i = 0; i < pos - 1; i++){t = t->next;}Plink p = malloc(sizeof(Link));p->data = e;p->next = t->next;t->next = p;L->len++;return 0;
}//在任意位置删除
int anypos_dele(Plink L, int pos)
{if (pos<1 || pos>L->len || L->len == 0 || L == NULL){printf("删除失败\n");return -1;}Plink t = L;int i;for (i = 0; i < pos - 1; i++){t = t->next;}Plink Q = t->next;t->next = t->next->next;free(Q);Q = NULL;L->len--;return 0;
}//逆置
int nizhi(Plink L)
{Plink Q = L->next;Plink t = Q->next;while (t != NULL){Q->next = t->next;t->next = L->next;L->next = t;t = Q->next;}return 0;
}//冒泡排序
int bublu(Plink L)
{int i;Plink j;stu temp;for (i = 1; i < L->len; i++){for (j = L->next; j->next != NULL; j = j->next){if (j->data.score > j->next->data.score){temp = j->data;j->data = j->next->data;j->next->data = temp;}}}
}//主函数
int main(int argc, const char* argv[])
{stu a[5] = { {1001,"小张",90},{1003,"小王",95},{1002,"小刘",88},{1005,"小杨",99},{1004,"小邢",89} };Plink L = create();int i;for (i = 0; i < 5; i++){front_insert(L, a[i]);//头插法}output_link(L);stu e = { 1009,"小李",99 };anypos_insert(L, 2, e);output_link(L);anypos_dele(L, 2);output_link(L);nizhi(L);output_link(L);bublu(L);output_link(L);return 0;
}