#include <stdio.h>
#include <stdlib.h>
typedef int data;
struct Slist
{
data a; //数据、结点
struct Slist* next; //结构体指针,指向下一个结点
};
typedef struct Slist STLnode;
void Slistprint(STLnode* phead); //打印
void SlistPushback(STLnode** pphead,data x); //尾插
void SlistPopback(STLnode** pphead); //尾删
void SlistPushHead(STLnode** pphead, data x); //头插
void SlistPopHead(STLnode**pphead); //头删
STLnode* Slistfind(STLnode* phead, data x); //找元素
void SlistInster(STLnode**pphead, STLnode*pos, data x); //任意插入,在第几个pos前插入
void SlistErase(STLnode**pphead, STLnode*pos); //任意删除
//实现模块 list.c
#include "List.h"
void Slistprint(STLnode* phead) //打印
{
STLnode* cut = phead;
while (cut != NULL)
{
printf("%d->",cut->a);
cut = cut->next;
}
printf("NULL\n");
}
void SlistPushback(STLnode** pphead, data x) //尾插
{
STLnode*newnode = (STLnode*)malloc(sizeof(STLnode)); //开辟一个新结点
newnode->a = x;
newnode->next = NULL;
if (*pphead == NULL) //如果pphead为空,newnode就是第一个结点
{
*pphead = newnode;
}
else //pphead不为空
{
STLnode* tail = *pphead;
while (tail->next != NULL) //找尾节点
{
tail = tail->next;
}
tail->next = newnode; //找到赋值
}
}
void SlistPopback(STLnode** pphead) //尾删
{
if (*pphead == NULL) //没有结点
{
return;
}
else if ((*pphead)->next == NULL) //有一个结点
{
free(*pphead);
*pphead = NULL;
}
else //一个节点以上
{
STLnode* prev = NULL; //prev跟在tail的后面
STLnode* tail = *pphead;
while (tail->next != NULL)
{
prev = tail;
tail = tail->next;
}
free(tail);
prev->next = NULL;
}
}
void SlistPushHead(STLnode** pphead, data x) //头插
{
STLnode*newnode = (STLnode*)malloc(sizeof(STLnode));
newnode->a = x;
newnode->next = NULL;
newnode->next = *pphead;
*pphead = newnode;
}
void SlistPopHead(STLnode**pphead) //头删
{
STLnode* next = (*pphead)->next;
free(*pphead);
*pphead = NULL;
*pphead = next; //再把下一个结点传给pphead
}
STLnode* Slistfind(STLnode* phead, data x) //找元素
{
STLnode* cut = phead;
while (cut)
{
if (cut->a == x)
{
return cut;
}
cut = cut->next;
}
return NULL;
}
void SlistInster(STLnode**pphead, STLnode*pos, data x) //任意插入 pos是位置 x是插入值
{
if (pos == *pphead) //如果是头插
{
SlistPushHead(pphead, x);
}
else //不是头插(任意插入)
{
STLnode* newnode = (STLnode*)malloc(sizeof(STLnode));
newnode->a = x;
newnode->next = NULL;
STLnode* prev = *pphead;
while (prev->next != pos) //没有找到想插入的位置就继续找
{
prev = prev->next;
}
//找到想插入的位置
prev->next = newnode;
newnode->next = pos;
}
}
void SlistErase(STLnode**pphead, STLnode*pos) //任意删除
{
if (pos == *pphead)
{
SlistPopHead(pphead);
}
else
{
STLnode* prev = *pphead;
while (prev->next != pos)
{
prev = prev->next;
}
prev->next = pos->next;
free(pos);
}
}
//主函数模块 main.c
#include "List.h"
void seqlist1()
{
STLnode* Plist = NULL; //Plist是头指针,指向第一个结点
SlistPushback(&Plist, 1);
SlistPushback(&Plist, 2);
SlistPushback(&Plist, 3);
SlistPushback(&Plist, 4);
Slistprint(Plist);
STLnode* pos = Slistfind(Plist, 2); //在第二个位置插入
if (pos)
{
SlistInster(&Plist, pos, 30); //插入30
}
Slistprint(Plist);
}
int main()
{
seqlist1();
return 0;
}