定义结构体
结构体成员包括:结点保存的数据和下一个结点的结构体指针
typedef int SLTDataType;
typedef struct SingleList
{
SLTDataType data;
struct SingleList* next;
}SLT;
函数实现
链表打印
void SLTprint(SLT* phead)
{
assert(phead);
while (phead != NULL)
{
printf("%d->", phead->data);
phead = phead->next;
}
printf("NULL\n");
}
链表结点的创建和赋值
SLT* SLTMemCrt(SLTDataType x)
{
SLT* new = (SLT*)malloc(sizeof(SLT));
if (NULL == new)
{
perror("malloc fail");
return NULL;
}
new->data = x;
return new;
}
链表的头插
void SLTpushfront(SLT** pphead, SLTDataType x)
{
assert(pphead);
SLT* new = SLTMemCrt(x);
new->next = *pphead;
*pphead = new;
}
链表的头删
void SLTpopfront(SLT** pphead)
{
assert(pphead);
assert(*pphead);
SLT* tmp = (*pphead)->next;
free(*pphead);
*pphead = tmp;
}
链表的尾插(链表尾插效率低,一般不用)
void SLTpushback(SLT** pphead, SLTDataType x)
{
assert(pphead);
SLT* new = SLTMemCrt(x);
SLT* cur = *pphead;
if (cur == NULL)
{
*pphead = new;
}
else
{
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next = new;
}
new->next = NULL;
}
链表的尾删(效率低,一般不用)
void SLTpopback(SLT** pphead)
{
assert(pphead);
assert(*pphead);
SLT* cur = *pphead;
if (cur->next == NULL)
{
free(cur);
*pphead = NULL;
}
else
{
while (cur->next->next != NULL)
{
cur = cur->next;
}
free(cur->next);
cur->next = NULL;
}
}
链表数据查找,返回结点指针
SLT* SLTFind(SLT* phead, SLTDataType x)
{
if (phead == NULL) //链表为空
return NULL;
while (phead->next != NULL)
{
if (phead->data == x)
return phead;
else
phead = phead->next;
}
printf("not found\n");
return NULL;
}
链表某数据后插入
void SLTInsertAfter(SLT** pphead, SLTDataType fdata, SLTDataType x)
{
//fdata表示要插入x的前一个位置的值
assert(pphead);
SLT* des = SLTFind(*pphead, fdata);
SLT* new = SLTMemCrt(x);
if(des == NULL)
{
printf("insert fail\n");
return;
}
else
{
new->next = des->next;
des->next = new;
}
}
链表某数据前插入
void SLTInsertFront(SLT** pphead, SLTDataType fdata, SLTDataType x)
{
//fdata表示要插入x的后一个位置的值
assert(pphead);
SLT* des = SLTFind(*pphead, fdata);
SLT* new = SLTMemCrt(x);
//遍历找到des的前一个结点的指针,效率低
//这里在des后插入一个结点,将值互换也可达到目的
if (des == NULL)
{
printf("insert fail\n");
return;
}
else
{
//值交换
new->data = des->data;
des->data = x;
//后插入结点
new->next = des->next;
des->next = new;
}
}
链表某数据后删除
void SLTEraseAfter(SLT** pphead, SLTDataType fdata)
{
assert(pphead);
assert(*pphead);
SLT* des = SLTFind(*pphead, fdata);
if (des == NULL || des->next == NULL)
{
printf("erase fail\n");
}
SLT* del = des->next;
des->next = del->next;
free(del);
}
链表某数据前删除
void SLTEraseFront(SLT** pphead, SLTDataType fdata)
{
assert(pphead);
assert(*pphead);
SLT* des = SLTFind(*pphead, fdata);
if (des == NULL || des == *pphead)
{
printf("erase fail\n");
return;
}
SLT* cur = *pphead;
if (cur->next == NULL)
{
free(cur);
*pphead == NULL;
return;
}
while (cur->next->next != des)
{
cur = cur->next;
}
free(cur->next);
cur->next = des;
}
链表全释放
void SLTDestory(SLT** pphead)
{
assert(pphead);
SLT* cur = *pphead;
if (cur == NULL)
return;
do
{
SLT* tmp = cur->next;
free(cur);
cur = tmp;
} while (cur != NULL);
*pphead = NULL;
}