头文件
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int ListData;
struct List
{
ListData num;
struct List* next;
};
void Listpushback(struct List **p,ListData x);//尾插
void Listpopback(struct List** p);//尾删
void Listpushhead(struct List** p, ListData x);//头插
void Listpophead(struct List** p);//头删
struct List* Listfind(struct List* p, ListData x);//查找
void Listdev(struct List* pos);//删除x之后的值
void Listadd(struct List* pos, ListData x);//在pos位置之后插入x;
void Listprint(struct List* p);//打印
struct List* Listnode(ListData x);//开辟结点
函数实现文件
#include"head.h"
struct List* Listnode(ListData x)//开辟结点
{
struct List* node = (struct List*)malloc(sizeof(struct List));
if (node == NULL)
{
perror("Listpushback");
exit(-1);
}
node->num = x;
node->next = NULL;
return node;
}
void Listpushback(struct List **p,ListData x)//尾插
{
struct List* node = Listnode(x);
if (*p == NULL)
{
*p = node;
}
else
{
//找尾
struct List* cur = *p;
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next = node;
}
}
void Listpopback(struct List** p)//尾删
{
if (*p==NULL)//无结点(这一步很重要的作用是为下一步的cur->next铺垫,
{ //如果没有这一步,下一步可能对空指针解引用了)
return;
}
else if ((*p)->next== NULL)//一个结点
{
free(*p);
*p= NULL;
}
else//1个以上结点
{
struct List* cur = *p;
struct List* give = cur;
while (cur->next != NULL)
{
give = cur;
cur = cur->next;
}
free(cur);
cur = NULL;
give->next = NULL;
}
}
void Listpushhead(struct List** p, ListData x)//头插
{
struct List* cur =Listnode(x);
cur->next = *p;
*p = cur;
}
void Listpophead(struct List** p)//头删
{
if (*p==NULL)//无结点
{
return;
}
else//一个或以上结点
{
struct List* next = (*p)->next;
free(*p);
*p = next;
}
}
struct List* Listfind(struct List* p, ListData x)//查找
{
if (p==NULL)//无结点
{
return NULL;
}
else //一个或以上结点
{
while (p->next != NULL)
{
if (p->num == x)
{
return p;
}
p = p->next;
}
if (p->num == x)//判断尾结点
{
return p;
}
printf("无此值");
return NULL;
printf("\n");
}
}
void Listadd(struct List* pos, ListData x)//在pos位置之后插入x
{
assert(pos);
struct List* newnode = Listnode(x);
newnode->next = pos->next;
pos->next = newnode;
}
void Listdev(struct List* pos)//删除pos之后的值
{
assert(pos);
if (pos->next)
{
struct List* next = pos->next;
pos->next = next->next;
free(next);
}
}
void Listprint(struct List* p)//打印
{
struct List* cur = p;
while (cur != NULL)
{
printf("%d->", cur->num);
cur = cur->next;
}
}