第一次尝试简单链表的实现
项目头文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _Node {
int value;
struct _Node *next;
} node;
node* make_empty(void); //创建一个头结点
node* make_new(int n); //创建一个结点
void add_end(node *prenode,int n); //在最后添加一个结点
int empty_list(node *p_node); //判断链表是否为空
int clean_mid(node *prenode); //删除下一个结点
int clean_list(node *first_node); //删除整个链表
void printf_list(node *first_node); //打印整个链表
具体函数
#include "fun.h"
//创建一个头结点
node* make_empty(void) {
node *p_node = (node*)malloc(sizeof(node));
p_node->value = 0;
p_node->next = NULL;
return p_node;
}
//创建一个结点
node* make_new(int n) {
node *p_node = (node*)malloc(sizeof(node));
p_node->value = n;
p_node->next = NULL;
return p_node;
}
//在最后添加一个结点
void add_end(node *prenode,int n) {
// ????
while(prenode->next) {
prenode = prenode->next;
}
prenode->next = make_new(n);
}
//判断链表是否为空
int empty_list(node *p_node) {
if(p_node->next) {
// printf("The list is not empty.\n");
return 0;
} else {
printf("The list is empty.\n");
return 1;
}
}
删除最后一个结点
//int clean_end(node *endnode) {
// if(empty_list(endnode) != 0) {
// endnode->value = 0;
// endnode->next = NULL;
// free(endnode);
// }
// return 1;
//}
//删除下一个结点
int clean_mid(node *prenode) {
if(empty_list(prenode)) {
return 0;
} else {
node *p_node = prenode->next;
node *next_node = p_node->next ;
prenode->next = next_node;
p_node->next = NULL;
p_node->value = 0;
free(p_node);
return 1;
}
}
//删除整个链表
int clean_list(node *first_node) {
if(empty_list(first_node)){
return 0;
}
// node *sed_node = first_node->next;
// node *ther_node = sed_node->next;
//删除头结点
// first_node->next = NULL;
// first_node->value = 0;
// free(first_node);
//删除中间的结点
node *prenode = first_node;
while(prenode->next != NULL) {
prenode = first_node->next ;
clean_mid(prenode);
}
prenode->next = NULL;
prenode->value = 0;
free(prenode);
return 1;
}
//打印整个链表
void printf_list(node *first_node) {
if(empty_list(first_node)) {
return ;
} else {
first_node=first_node->next ;
while(first_node) {
printf("%d\n",first_node->value);
first_node=first_node->next;
}
}
}
测试用例
#include "fun.h"
int main(int argc,char* argv[])
{
node *a=make_empty();
printf("1:\n");
printf_list(a);
a->next=make_new(1);
printf("2:\n");
printf_list(a);
add_end(a,2);
printf("3:\n");
printf_list(a);
clean_mid(a);
printf("4:\n");
printf_list(a);
printf("5:\n");
clean_list(a);
return 0;
}