单链表的端口实现
test.c为测试文件
SingleLinked.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
typedef int DadaType;
typedef struct SingleLinkedList
{
DadaType content;
struct SingleLinkedList* next;
}SinLin;
//打印单链表
void PrintSingle(SinLin* phead);
//动态内存释放
void FreeMemory(SinLin** phead);
//尾插单链表
void PushBack(SinLin** phead, DadaType n);
//头插单链表
void PushFront(SinLin** phead, DadaType n);
//尾删单链表
void PopBack(SinLin** phead);
//头删单链表
void PopFront(SinLin** phead);
//寻找节点
SinLin* FindNode(SinLin* phead, DadaType n);
//在节点前插入链表
void InsertFrontNode(SinLin** phead, SinLin* pos, DadaType n);
//在节点后插入链表
void InsertBehindNode(SinLin* pos, DadaType n);
//删除节点链表
void EraseNode(SinLin** phead, SinLin* pos);
//删除节点后的链表
void EraseFrontNode(SinLin* pos);
SingleLinked.c
#include "SingleLinked.h"
SinLin* create(DadaType n)
{
//创建一个结构体
SinLin* ps = (SinLin*)malloc(sizeof(SinLin));
if (NULL == ps)
{
printf("%s\n", strerror(errno));
exit(-1);
}
ps->content = n;
ps->next = NULL;
return ps;
}
void FreeMemory(SinLin** phead)
{
assert(*phead);
SinLin* pstr = *phead;
while (pstr)
{
SinLin* ps = pstr->next;
free(pstr);
pstr = ps;
}
*phead = NULL;
}
void PrintSingle(SinLin* phead)
{
SinLin* p = phead;
while (p)
{
printf("%d->", p->content);
p = p->next;
}
printf("NULL\n");
}
void PushBack(SinLin** phead, DadaType n)
{
SinLin* pstr = create(n);
if (NULL == *phead)
{
*phead = pstr;
}
else
{
SinLin* p = *phead;
while (p->next)
{
p = p->next;
}
p->next = pstr;
}
}
void PushFront(SinLin** phead, DadaType n)
{
assert(*phead);
SinLin* pstr = create(n);
pstr->next = *phead;
*phead = pstr;
}
void PopBack(SinLin** phead)
{
assert(*phead);
if((*phead)->next)
{
SinLin* pstr = *phead;
while (pstr->next->next)
{
pstr = pstr->next;
}
free(pstr->next);
pstr->next = NULL;
}
else
{
free(*phead);
*phead = NULL;
}
}
void PopFront(SinLin** phead)
{
assert(*phead);
SinLin* pstr = (*phead)->next;
free(*phead);
*phead = pstr;
}
SinLin* FindNode(SinLin* phead, DadaType n)
{
while (phead)
{
if (n == phead->content)
{
return phead;
}
else
{
phead = phead->next;
}
}
return NULL;
}
void InsertFrontNode(SinLin** phead, SinLin* pos, DadaType n)
{
assert(*phead);
SinLin* pstr = create(n);
if (pos == *phead)
{
pstr->next = *phead;
*phead = pstr;
}
else
{
SinLin* ps = *phead;
while (pos != ps->next)
{
ps = ps->next;
}
pstr->next = pos;
ps->next = pstr;
}
}
void InsertBehindNode(SinLin* pos, DadaType n)
{
SinLin* pstr = create(n);
pstr->next = pos->next;
pos->next = pstr;
}
void EraseNode(SinLin** phead, SinLin* pos)
{
assert(*phead);
//头删
SinLin* pstr = *phead;
if (pos == pstr)
{
*phead = pstr->next;
free(pstr);
}
else
{
SinLin* ps = *phead;
while (pos != pstr)
{
ps = pstr;
pstr = pstr->next;
}
ps->next = pstr->next;
free(pstr);
pstr = NULL;
}
}
void EraseFrontNode(SinLin* pos)
{
SinLin* pstr = pos;
if(NULL != pstr->next)
{
pstr->next = pstr->next->next;
free(pos->next);
}
}