链表:在逻辑上是线性的,物理结构不是连续的,链表是一个个节点(结点)连接成的结构。
链表的结构分为8种:

分文件 编写

这里的参数是二级指针重点说一下
在链表为空的时候头插尾插,要改变指针的指向
没有指针的地址是无法改变数据的,
#pragma once
#include
#include
#include
typedef int SDataType;
typedef struct SListNode
{
SDataType val;
struct SListNode* next;
}ListNode;
//链表销毁
void SListDestory(ListNode** phead);
//链表打印
void SListPrint(ListNode** phead);
//链表创建节点
ListNode* SListBuyNode(SDataType x);
//链表尾插
void SListPushBack(ListNode** phead, SDataType x);
//链表头插
void SListPushFront(ListNode** phead, SDataType x);
//链表尾删
void SListPopBack(ListNode** phead);
//链表头删
void SListPopFront(ListNode** phead);
//节点的查找
ListNode* SLFind(ListNode** phead, SDataType x);
//任意位置处插入
void SListInsert(ListNode* Pos,SDataType x);
//任意位置处插入
void SListEmarse(ListNode* Pos);
#include"SList.h"
//链表销毁
void SListDestory(ListNode** phead)
{
assert(phead);
assert(*phead);
ListNode* cur = *phead;
ListNode* del = NULL;
while (cur)
{
del = cur;
cur = cur->next;
free(del);
}
}
//链表打印
void SListPrint(ListNode** phead)
{
assert(phead);
assert(*phead);
ListNode* cur = *phead;
while (cur)
{
printf("%d -> ", cur->val);
cur = cur->next;
}
printf("\n");
}
//链表创建节点
ListNode* SListBuyNode(SDataType x)
{
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
if (node == NULL)
{
perror("malloc faile :");
printf("并且返回NULL");
return NULL;
}
//此时开辟空间成功
node->next = NULL;
node->val = x;
return node;
}
//链表尾插
void SListPushBack(ListNode** phead,SDataType x)
{
assert(phead);
ListNode* node = SListBuyNode(x);
//没有哨兵位的链表要判断链表是否空
if (*phead == NULL)
{
*phead = node;
}
else
{
ListNode* cur = *phead;
while (cur->next)
{
cur = cur->next;
}
cur->next = node;
}
}
//链表头插
void SListPushFront(ListNode** phead,SDataType x)
{
assert(phead);
ListNode* node = SListBuyNode(x);
if (*phead == NULL)
{
*phead = node;
}
else
{
ListNode* newhead = node;
newhead->next = *phead;
*phead = newhead;
}
}
//链表尾删
void SListPopBack(ListNode** phead)
{
assert(phead);
assert(*phead);
if ((*phead)->next == NULL)
{
free(*phead);
*phead = NULL;
}
else
{
ListNode* cur = *phead;
ListNode* prev = NULL;
while (cur->next)
{
prev = cur;
cur = cur->next;
}
prev->next = NULL;
free(cur);
}
}
//链表头删
void SListPopFront(ListNode** phead)
{
assert(phead);
assert(*phead);
if ((*phead)->next == NULL)
{
free(*phead);
*phead = NULL;
}
else
{
ListNode* next = (*phead)->next;
free(*phead);
*phead = next;
}
}
//节点的查找
ListNode* SLFind(ListNode** phead,SDataType x)
{
assert(phead);
assert(*phead);
ListNode* cur = *phead;
while (cur)
{
if (cur->val == x)
{
return cur;
}
cur = cur->next;
}
printf("没有找到,并且返回了NULL\n");
return NULL;
}
//任意位置后处插入
void SListInsert(ListNode* Pos, SDataType x)
{
assert(Pos);
ListNode* node = SListBuyNode(x);
ListNode* next = Pos->next;
Pos->next = node;
node->next = next;
}
//任意位置后处删除
void SListEmarse(ListNode* Pos)
{
assert(Pos);
assert(Pos->next);
ListNode* del = Pos->next;
if (del->next == NULL)
{
free(del);
Pos->next = NULL;
}
else
{
Pos->next = del->next;
free(del);
}
}