学习了有一段时间C++和C,本来想查找链表(linked structures)的具体实现,可是发现网络上大多的实现方法不太简单便捷,所以自己设计了一套代码如下, 并且我运用了我20年的画画技术,为大家手绘一个思路图方便理解,(PS:因为国外待太久,字丑不要介意哈)
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
/* 定义了一个struct 分为数据地址和一个指向下个struct的指针*/
typedef struct node node_t;
struct node {
data_t data;
node_t *next;
};
/* 定义一个空链表,并且head表示指向链表的首部的指针,foot为尾部*/
typedef struct {
node_t *head;
node_t *foot;
} list_t;
/*创建一个空链表,并且返回指向链表的指针*/
list_t *make_empty_list(void) {
list_t *list;
list = (list_t*)malloc(sizeof(*list));
assert(list!=NULL); //判断链表是否建立成功
list->head = list->foot = NULL;
return list;
}
/* 释放链表*/
void free_list(list_t *list) {
node_t *curr, *prev;
assert(list!=NULL);
curr = list->head;
while (curr) {
prev = curr;
curr = curr->next;
free(prev);
}
free(list);
}
/* 插入一个新的数据在尾部*/
list_t *insert_at_foot(list_t *list, data_t value) {
node_t *new1;
new1 = (node_t*)malloc(sizeof(*new1));
assert(list!=NULL && new1!=NULL);
new1->data = value;
new1->next = NULL;
if (list->foot==NULL) {
/* 这里是第一次插入的时候 */
list->head = list->foot = new1;
} else {
list->foot->next = new1;
list->foot = new1;
}
return list;
}
/* 插入一个新的数据在头部*/
list_t *insert_at_head(list_t *list, data_t value) {
node_t *new1;
new1 = (node_t*)malloc(sizeof(*new1));
assert(list!=NULL && new1!=NULL);
new1->data = value;
new1->next = list->head;
list->head = new1;
if (list->foot==NULL) {
/* 这里是第一次插入的时候 */
list->foot = new1;
}
return list;
}
结尾,在学习c++过后,推荐使用new 来代替malloc这样效率高