typedef int E;
//结点
typedef struct Node{
E data;
struct Node* next;
} Node;
//链表
typedef struct List{
Node* head;
Node* tail;
int size;
} List;
//创建链表
List* list_create(void) {
return calloc(1, sizeof(List));
}
//删除链表
void list_destroy(List* list) {
Node* cur = list->head;
Node* guard = cur;
while (guard) {
guard = guard->next;
free(cur);
cur = guard;
}
free(list);
}
//头插法
void add_before_head(List* list, E val) {
Node* newNode = malloc(sizeof(Node));
if (!newNode) {
printf("Error: malloc failed\n");
exit(1);
}
newNode->data = val;
newNode->next = list->head;
list->head = newNode;
if (!list->tail) { //空链表
list->tail = newNode;
}
list->size++;
}
//尾插法
void add_behind_head(List* list, E val) {
Node* newNode = malloc(sizeof(Node));
if (!newNode) {
printf("Error: malloc failed\n");
exit(1);
}
newNode->data = val;
newNode->next = NULL;
if (!list->tail) { //空链表
list->head = newNode;
list->tail = newNode;
}else {
list->tail->next = newNode;
list->tail = newNode;
}
list->size++;
}
//打印链表
void print_list(List* list) {
Node* cur = list->head;
if (!cur) printf("No node in linked list\n");
else {
printf("linked list: ");
while (cur) {
printf("%d ", cur->data);
cur = cur->next;
}
}
printf("\n");
}
//插入结点
void add_node(List* list, E index, E val) {
if (index < 0 || index > list->size) {
printf("Illegal Argument: size = %d, index = %d\n", list->size, index);
return;
}
//加到最前面,头插法
if (index == 0) {
add_before_head(list, val);
return;
}
//加到最后面,尾插法
if (index == list->size) {
add_behind_head(list, val);
return;
}
//加中间
Node* cur = list->head;
index--;
while (index--) {
cur = cur->next;
}
Node* newNode = malloc(sizeof(Node));
if (!newNode) {
printf("Error: malloc failed\n");
exit(1);
}
newNode->data = val;
newNode->next = cur->next;
cur->next = newNode;
list->size++;
}
//删除结点
void delete_node(List* list, E val) {
Node* pre = NULL;
Node* cur = list->head;
while (cur) {
if (cur->data == val) {
if (pre == NULL) { //删头结点
list->head = cur->next;
if (list->tail == cur) { //就一个结点
list->tail = NULL;
}
}else {
pre->next = cur->next;
if (list->tail == cur) { //删尾结点
list->tail = pre;
}
}
free(cur);
list->size--;
return;
}
pre = cur;
cur = cur->next;
}
printf("There is no node with value %d in the linked list\n", val);
}
//给下标,查结点
Node* find_by_index(List* list, E index) {
if (index < 0 || index >= list->size) {
return NULL;
}else {
Node* cur = list->head;
while (index--) {
cur = cur->next;
}
return cur;
}
}
//给值,查结点
Node* find_by_value(List* list, E val) {
Node* cur = list->head;
while (cur) {
if (cur->data == val) {
return cur;
}
cur = cur->next;
}
return NULL;
}
【C语言】19_结构体实现链表的增删查输出
于 2024-05-11 08:54:51 首次发布