文章目录
链表(思路一)
普通单向链表
初始化
2020年10月08日
缺点:
- 结构体设计没有通用性
int val
换成void *data
#include <stdio.h>
#include <stdlib.h>
struct LinkNode
{
int val;
struct LinkNode *next;
} l;
void destroy(struct LinkNode *node)
{
if (node == NULL)
{
return;
}
struct LinkNode *next = node->next;
free(node);
printf("(destroy)%p\n", node);
if (next != NULL)
{
destroy(next);
}
}
void show(struct LinkNode *first)
{
if (first == NULL)
{
return;
}
printf("%p %d\n", first, first->val);
if (first->next != NULL)
{
show(first->next);
}
}
void build(struct LinkNode **first, int *vals, int len)
{
if (len > 0)
{
*first = malloc(sizeof(struct LinkNode));
(*first)->val = vals[0];
build(&(*first)->next, vals + 1, len - 1);
}
else
{
*first = NULL;
}
}
void test()
{
struct LinkNode *node1;
int vals[] = {
1, 2, 3, 4, 5, 6};
int len = sizeof(vals) / sizeof(vals[0]);
build(&node1, vals, len);
show(node1);
destroy(node1);
}
int main(int argc, char *argv[])
{
test();
return 0;
}
插入、删除(add_next、remove_next)
void add_next(struct LinkNode *first, struct LinkNode *node)
{
if (first == NULL || node == NULL)
{
return;
}
// 合并尾部
struct LinkNode *end = node;
while (end->next != NULL)
{
end = end->next;
}
end->next = first->next;
// 合并前面
first->next = node;
}
void remove_next(struct LinkNode *node)
{
if (node == NULL || node->next == NULL)
{
return;
}
struct LinkNode *next = node->next->next;
free(node->next);
node->next = next;
}
void test()
{
struct LinkNode *node1;
int vals[] = {
1, 2, 3, 4, 5, 6};
int len = sizeof(vals) / sizeof(vals[0]);
printf("\n-------原始-------\n");
build(&node1, vals, len);
show(node1);
printf("\n-------删除-------\n");
remove_next(node1);
// 1 3 4 5
remove_next(node1->next->next->next);
show(node1);
printf("\n-------增加-------\n");
struct LinkNode *nodel2;
int vals2[] = {
11, 22, 33, 44};
int len2 = sizeof(vals2) / sizeof(vals2[0]);
build(&nodel2, vals2, len2);
add_next(node1->next, nodel2);
show(node1);
printf("\n-------清理-------\n");
destroy(node1);
}
链表(思路二)
https://www.bilibili.com/video/BV13b411V73v?p=284
首地址可以表示用户数据,也可以表示node
#include <stdio.h>
#include <stdlib.h>
struct LinkNode
{
struct LinkNode *next;
};
struct LinkList
{
struct LinkNode header;
int size;
};
typedef void *List;
// 初始化链表
List init_LinkList()
{
struct LinkList *list = malloc(sizeof(List));
if (NULL == list)
{
// log...
return NULL;
}
list->header.next = NULL;
list->size = 0;
return list;
}
//
void insert_LinkList(List list, int offset, void *data)
{
if (list == NULL)
{
// log...
return;
}
struct LinkList *myList = (struct LinkList *)list;
struct LinkNode *newNode = (struct LinkNode *)data;
// 下标
if (0 > offset)
{
offset = 0;
}
else if (offset >= myList->size)
{
offset = myList->size;
}
//
struct LinkNode *previousNode = &myList->header;
for (int i = 0; i < offset; i++)
{
previousNode = previousNode->next;
}
if (previousNode->next == NULL)
{
previousNode->next = newNode;
(myList->size)++;
}
else
{
if (newNode != NULL)
{
newNode->next