#pragma once
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
typedef int data_t;
typedef struct node
{
data_t data;//成员数据类型
struct node* next;//存放下一结点地址
}listnode, *linklist;
//无特殊说明时,@ret -1代表操作失败 0代表操作成功
//创建一个节点,返回头结点地址,失败返回NULL
linklist link_creat();
//链表尾部插入
void link_tail(linklist p, const data_t *val);
//链表清空
int link_clear(linklist p);
//按值删除链表中的节点
int link_delete(linklist p, data_t* val);
//按值查找链表,返回该值在链表第几个位置,失败返回-1
int link_find(linklist p, const data_t* sour);
//在链表的第几个位置插入指定值的新节点
int link_insert(linklist p, int pos, const data_t* val);
//释放链表动态空间,传递二级指针,便于将头结点指针置NULL
void link_free(linklist* p);
//遍历打印链表
void link_show(linklist p);
头文件LinkList.h
#include "LinkedList.h"
linklist link_creat()
{
linklist p;
p = (linklist)malloc(sizeof(listnode));
if (p == NULL)
{
printf("Pointer is NULL.\n");
return NULL;
}
p->data = 0;
p->next = NULL;
return p;
}
void link_tail(linklist p, const data_t* val)
{
if (p == NULL)
{
printf("Pointer is NULL.\n");
return;
}
linklist newnode;
newnode = link_creat();
newnode->data = *val;
if (newnode == NULL)
{
printf("Malloc Error.\n");
}
while (p->next != NULL)
{
p = p->next;
}
p->next = newnode;
}
int link_clear(linklist p)
{
if (p == NULL)
{
printf("Pointer is NULL.\n");
return -1;
}
linklist temp;
temp = p;
while (p != NULL)
{
temp = p;
p = p->next;
temp->data = 0;
temp->next = NULL;
}
return 0;
}
int link_delete(linklist p, data_t* val)
{
int i = 0;
if (p == NULL)
{
printf("Pointer is NULL.\n");
return -1;
}
int ret = link_find(p, val) - 1;
if (ret == -1)
{
printf("Value Not found.\n");
return -1;
}
else
{
while (i < ret)
{
p = p->next;
i++;
}
p->next = p->next->next;
return 0;
}
}
int link_find(linklist p, const data_t* sour)
{
if (p == NULL)
{
printf("Pointer is NULL.\n");
return -1;
}
int pos = 0;
while (p != NULL)
{
if (p->data == *sour)
{
return pos;
}
p = p->next;
pos++;
}
return -1;
}
int link_insert(linklist p, int pos, const data_t* val)
{
int i = 1;
if (p == NULL)
{
printf("Pointer is NULL.\n");
return -1;
}
linklist newnode;
newnode = link_creat();
while (i < pos)
{
p = p->next;
i++;
if (pos < 0 || p == NULL)
{
//插入位置太大或太小
printf("Input Wrong.\n");
return -1;
}
}
newnode->next = p->next;
newnode->data = *val;
p->next = newnode;
return 0;
}
void link_show(linklist p)
{
linklist temp;
if (p == NULL)
{
printf("Pointer is NULL.\n");
return;
}
temp = p;
while (temp->next != NULL)
{
printf("%d\t%p\n",temp->next->data, temp);
temp = temp->next;
}
printf("\n");
}
void link_free(linklist* p)
{
if (*p == NULL)
{
printf("Pointer is NULL.\n");
return;
}
linklist temp;
temp = *p;
while (*p != NULL)
{
temp = *p;
*p = (*p)->next;
free(temp);
}
*p = NULL;
}
LinkList.c 函数功能实现
#include "LinkedList.h"
int main()
{
linklist p;
p = link_creat();
//测试部分
//
return 0;
}
test.c 测试函数功能
又犯了很多次愚蠢的错误,对空指针解引用,指针越界访问,操作不属于动态开辟的内存空间。这种错误相比语法错误不好调试,特别是循环当中,循环的起始条件,终止条件,条件修改和语句顺序都有影响。还好VS使用未初始化的野指针会报语法错误,不然我的内存报错还会更多。