单向动态链表掌握以下函数就足够了:
#include <stdio.h>
#include <stdlib.h>
typedef struct _node
{
int value;
struct _node *next;
} Node;
typedef struct _list
{
Node *head;
} List;
// 创建节点
Node *creat_node(int value)
{
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->value = value;
new_node->next = NULL;
return new_node;
}
// 头插
void head_insert(List *list, int value)
{
Node *new_node = creat_node(value);
new_node->next = list->head;
list->head = new_node;
}
// 尾插
void tail_insert(List *list, int value)
{
Node *new_node = creat_node(value);
if (!list->head)
{
list->head = new_node;
}
else
{
Node *current = list->head;
for (; current->next; current = current->next)
;
current->next = new_node;
}
}
// 搜索节点
Node *search_node(List *list, int value)
{
Node *current = list->head;
for (; current != NULL && current->value != value; current = current->next)
;
return current;
}
// 删除节点
void delete_node(List *list, int value)
{
for (Node *current = list->head, *prev = NULL; current; prev = current, current = current->next)
{
if (current->value == value)
{
if (prev)
{
prev->next = current->next;
}
else
{
list->head = current->next;
}
free(current);
break;
}
}
}
// 打印链表
void print_list(List *list)
{
for (Node *current = list->head; current; current = current->next)
{
printf("%d ", current->value);
}
printf("\n");
}
// 清除链表
void clear_list(List *list)
{
for (Node *current = list->head, *subs; current; current = subs)
{
subs = current->next;
free(current);
}
}
// 一个例子
int main()
{
List list;
list.head = NULL;
int a, b, c, d, e, x;
printf("Please enter 5 integers:");
scanf("%d%d%d%d%d", &a, &b, &c, &d, &e);
tail_insert(&list, c);
tail_insert(&list, d);
tail_insert(&list, e);
printf("After tail insert:");
print_list(&list);
head_insert(&list, b);
head_insert(&list, a);
printf("After head insert:");
print_list(&list);
printf("Please enter an integer:");
scanf("%d", &x);
if (search_node(&list, x))
printf("%d is found\n", x);
else
printf("%d is not found\n", x);
delete_node(&list, d);
printf("After delete node:");
print_list(&list);
clear_list(&list);
printf("The linked list is cleared\n");
return 0;
}