#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct {
char name[20];
int age;
bool sex;
} Student;
typedef Student LinkType;
// 节点结构体
typedef struct _Node{
LinkType data;
struct _Node* next;
} Node;
// 链表结构体
typedef struct {
Node* head;
} Linklist;
bool linklist_init(Linklist* plist){
if(NULL == plist) return false;
plist->head = NULL;
return true;
}
bool linklist_append(Linklist* plist,LinkType element){
// 参数检查
// 创建一个新节点
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = element;
new_node->next = NULL;
// 如果链表为空
if(NULL == plist->head){
plist->head = new_node;
}else{
// 查找最后一个节点
Node* p = plist->head;
while(NULL != p->next){
p = p->next;
}
// 把新节点加到最后节点后面
p->next = new_node;
}
return true;
}
bool linklist_prepend(Linklist* plist,LinkType element){
// 创建一个新节点
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = element;
new_node->next = NULL;
if(NULL == plist->head){
plist->head = new_node;
}else{
new_node->next = plist->head;
plist->head = new_node;
}
return true;
}
int linklist_size(Linklist* plist){
Node* p=plist->head;
int size = 0;
// 遍历链表中所有节点
while(NULL != p){
p = p->next;
++size;
}
//for(Node* p=plist->head;NULL != p;p=p->next){
// ++size;
//}
return size;
}
bool linklist_insert(Linklist* plist,int index,LinkType element){
if(NULL == plist) return false;
if(index <0 || index > linklist_size(plist)) return false;
// 头插入
if(0 == index){
return linklist_prepend(plist,element);
}
// 尾插入
if(index == linklist_size(plist)){
return linklist_append(plist,element);
}
// 创建一个新节点
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = element;
new_node->next = NULL;
Node* p = plist->head;
// 找到index节点前面的节点
for(int i=0;i<index-1;++i){
p = p->next;
}
new_node->next = p->next;
p->next = new_node;
return true;
}
LinkType linklist_get(Linklist* plist,int index){
// 参数检查
Node* p = plist->head;
for(int i=0;i<index;++i){
p=p->next;
}
return p->data;
}
void linklist_destroy(Linklist* plist){
Node* p = plist->head;
// 遍历链表所有节点
while(NULL != p){
Node* q = p->next;
free(p);
p = q;
}
}
void linklist_traverse(Linklist* plist,void(*func)(LinkType)){
Node* p = plist->head;
while(NULL != p){
(*func)(p->data);
p = p->next;
}
}
/
void print_int(int data){
printf("%d ",data);
}
void print_float(float data){
printf("%f ",data);
}
void print_student(Student s){
printf("姓名:%s\t年龄:%d,性别:%s\n",s.name,s.age,s.sex?"男":"女");
}
int main(){
Linklist list;
linklist_init(&list);
while(true){
Student s;
if(EOF == scanf("%s %d %d",s.name,&s.age,&s.sex)) break;
linklist_prepend(&list,s);
}
Student s = {"test",20,0};
linklist_insert(&list,2,s);
// int size = linklist_size(&list);
// for(int i=0;i<size;++i){
// printf("%d ",linklist_get(&list,i));
// }
linklist_traverse(&list,print_student);
printf("\n");
linklist_destroy(&list);
}
链表示例代码
最新推荐文章于 2022-09-09 18:45:42 发布