企业链表思路:企业链表 为 单向链表的改进,主要通过在数据结构顶端定义结点 每个结点相连 ,这样就可以把数据“串”起来;
代码如下,易错主要在结构体类型转换成结点类型这里; 还有自定义的函数指针;
#include "stdio.h"
#include "stdlib.h"
typedef struct LINKNODE
{
struct LINKNODE* next;
}LinkNode;
typedef struct LINKLIST
{
LinkNode* head;
int size;
}LinkList;
struct student
{
LinkNode* node;
char name[64];
int age;
int score;
};
typedef void(*PRINTNODE)(LinkNode*);
初始化链表;
LinkList* init_list(LinkList* list)
{
list = (LinkList*) malloc(sizeof(LinkList));
list->size = 0;
//list->head->next = NULL; //head 现在还没有地址,next 会出错 ;
return list;
}
void insert_list(LinkList* list, int pos, LinkNode* data)
{
LinkNode * finalNode = list->head;
if (list == NULL)
return;
if (data == NULL)
return;
if (pos<0 || pos > list->size)
return;
if (pos == 0)
{
list->head = data;
list->head->next = NULL;
list->size++;
}
else
{
finalNode = list->head;
for (int i = 1; i < pos; i++)
{
finalNode = finalNode->next;
if (finalNode == NULL)
return;
}
//现在 final在 pos的前一个位置;
finalNode->next = data;
finalNode->next->next = NULL;
list->size++;
}
}
//指定位置删除数据;
void remove_list(LinkList* list, int pos)
{
if (pos == 0)
{
LinkNode* node = list->head;
list->head = list->head->next;
free(node);
node = NULL;
list->size--;
}
else
{
LinkNode* tempNode = list->head;
for (int i = 1; i < pos; i++)
{
tempNode = tempNode->next;
if (tempNode == NULL)
return;
}
//现在tempNOde指向pos前一个位置;
tempNode->next = NULL;
list->size--;
//ListNode 是 struct student开启的 这里不用释放了;
}
}
void print_list(LinkList* list, PRINTNODE print)
{
LinkNode* tempNode = list->head;
if (list == NULL)
return;
while (tempNode != NULL)
{
//printf("11111111111\n");
//printf("%d ", *(int*)tempNode->data); //先转换为int指针 在用* 提取地址里的值;
print(tempNode);
tempNode = tempNode->next;
}
printf("总共有%d人\n", list->size);
}
void myPrint(LinkNode* node)
{
struct student* st = (struct student*)node;
printf("我叫%s,今年%d岁了,考了%2d分\n", st->name, st->age, st->score);
}
void destory_list(LinkList* list)
{
if (list != NULL)
{
free(list);
list = NULL;
}
}
int main()
{
LinkList* list = NULL;
list = init_list(list); //初始化链表;
struct student student1 = { NULL,"zhang3", 23, 100 };
struct student student2 = { NULL, "lisi", 21, 90 };
struct student student3 = { NULL, "wangwu", 43, 50 };
struct student student4 = { NULL, "111", 43, 50 };
printf("--------------------测试指定位置插入数据----------------------\n");
insert_list(list, 0, (LinkNode*)&student1);
insert_list(list, 1, (LinkNode*)&student2);
insert_list(list, 2, (LinkNode*)&student3);
insert_list(list, 3, (LinkNode*)&student4);
print_list(list,myPrint );
printf("--------------------测试指定位置删除数据----------------------\n");
remove_list(list, 3);
print_list(list, myPrint);
destory_list(list); //释放链表;
system("pause");
return 0 ;
}
运行截图;