包含了许多c语言的使用精华和编程习惯
单向循环链表的基本操作:
包含三个文件:
1.c为函数的实现
1.h为函数的声明
main.c为主函数
1.c文件:
/*************************************************************************
> File Name : 1.c
> Author : 潘潘的嵌入式
> Function : 单向循环链表
> Created Time: 2023年01月09日 星期一 09时07分32秒
************************************************************************/
#include "1.h"
//创建一个带头结点单向链表 并初始化
node_t* init_list()
{
node_t* head = (node_t*)malloc(sizeof(node_t));
SYSERR(NULL,==,head,"malloc is error",NULL);
head -> next = head;
head -> data = NULL;
return head;
}
//头插法建立单向循环链表
int insert_hlist(node_t *head,void *data,int size)
{
//参数检测
SYSERR(NULL,==,head,"head is NULL",-1);
SYSERR(NULL,==,data,"data is NULL",-1);
//创建新结点 并安全检查
node_t* newNode = (node_t*)malloc(sizeof(node_t));
SYSERR(NULL,==,newNode,"malloc is error",-2);
//给结点数据域赋值
newNode -> data = malloc(size);
SYSERR(NULL,==,newNode -> data,"malloc is error",-2);
memcpy(newNode -> data,data,size);
//插入链表
newNode -> next = head -> next;
head -> next = newNode;
return 0;
}
//尾插法建立循环单链表
int insert_tlist(node_t *head,void *data,int size)
{
//参数检测
SYSERR(NULL,==,head,"head is NULL",-1);
SYSERR(NULL,==,data,"data is NULL",-1);
//创建新结点 并安全检查
node_t* newNode = (node_t*)malloc(sizeof(node_t));
SYSERR(NULL,==,newNode,"malloc is error",-2);
//给结点数据域赋值
newNode -> data = malloc(size);
SYSERR(NULL,==,newNode -> data,"malloc is error",-2);
memcpy(newNode -> data,data,size);
//插入链表
node_t* temp = head;
while(temp -> next != head)
{
temp = temp -> next;
}
temp -> next = newNode;
newNode -> next = head;
return 0;
}
//计算数据结点个数
int list_len(node_t *head)
{
SYSERR(NULL,==,head,"head is null",-1);
node_t *temp = head -> next;
int count = 0;
while(temp != head)
{
++count;
temp = temp -> next;
}
return count;
}
//查找第i个位置的成员并且输出全部信息
int show_index(node_t *head,int index)
{
SYSERR(NULL,==,head,"head is null",-1);
if(index <= 0)
{
printf("%d位置不合法\n",index);
return -2;
}
index = index % (list_len(head) + 1);
if(!index)
{
printf("你输入的位置是头结点\n");
return -1;
}
node_t *temp = head;
int i = 0;
while(i < index)
{
++i;
temp = temp -> next;
}
show_list_all(temp -> data);
return 0;
}
//比较姓名
int cmpname(const void *data1,const void *data2)
{
stu_t *stu1 = (stu_t*)data1;
stu_t *stu2 = (stu_t*)data2;
return strcmp(stu1 -> name,stu2 -> name);
}
//比较年龄
int cmpage(const void *data1,const void *data2)
{
stu_t *stu1 = (stu_t*)data1;
stu_t *stu2 = (stu_t*)data2;
return stu1 -> age - stu2 -> age;
}
//比较学号
int cmpnum(const void *data1,const void *data2)
{
stu_t *stu1 = (stu_t*)data1;
stu_t *stu2 = (stu_t*)data2;
return stu1 -> num - stu2 -> num;
}
//比较成绩
int cmpgrade(const void *data1,const void *data2)
{
stu_t *stu1 =