单链表实现c语言-创新互联
#include
#include;
#include
//特别注意要传二级指针因为如果要改变一指针的值必须用二级指针,可以类比一下调用函数改变字母值
typedef int SLDataType; //下一个节点数据类型容易改变
typedef struct SListNode
{
SLDataType data;
struct SListNode* next;
}SListNode;//定义一个结构体储存数据和下一个节点地址
void SListInitNode(SListNode** plist)
{
assert(plist);
*plist = (SListNode*)malloc(sizeof(SListNode));
assert(*plist);
(*plist)->data = 0;
(*plist)->next = NULL;
} //初始化结构体;
void SListPrint(SListNode* phead)
{
SListNode* cur = phead;
while (cur != NULL)
{
printf("%d->", cur->next);
cur = cur->next;
}
}//打印函数
定义可以申请节点不必每次调用函数都要写,简化代码
SListNode* BuyListNode(SLDataType x)
{
SListNode* newnode = (SListNode*)malloc(sizeof(SListNode));
if (newnode == NULL)
{
printf("fail");
exit(-1);
}
newnode->data = x;
newnode->next = NULL;
return newnode;
}
//尾插
void SListPushBack(SListNode** plist, SLDataType x)
{
assert(plist);//避免空指针
SListNode* newnode = BuyListNode(x);
newnode->data = x;
newnode->next = NULL;
if (*plist == NULL)
{
*plist = newnode;
}
else
{
SListNode* tail = *plist;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = newnode;
}
}
//尾删
void SListPopBack(SListNode** plist)
{
if (*plist == NULL)
{
return;
}
assert(*plist != NULL);
SListNode* prev = NULL;
SListNode* tail = *plist;
while (tail->next)
{
prev = tail;
tail = tail->next;
}
free(tail);
tail = NULL;
if (prev)
{
prev->next = NULL;
}
}
//头删
void SListPopFront(SListNode** plist)
{
assert(*plist != NULL);
SListNode* next = (*plist)->next;
free(*plist);
*plist = next;
}
//头插
void SListNodePushFront(SListNode** plist, SLDataType x)
{
assert(*plist);
SListNode* newnode = BuyListNode(x);
newnode->next = *plist;
*plist = newnode;
}
//发现节点位置,发现这个节点后要在这个节点前面插入
SListNode* SListFind(SListNode* plist, SLDataType x)
{
SListNode* cur = plist;
while (cur)
{
if (cur->data == x)
{
return cur;
}
else
{
cur = cur->next;
}
}
return NULL;
}
//在任意位置插入;前面的代码尾插,尾删,头插,头删又可以嵌套这个在任意位置插入的代码极大的改变代码长度
void SListInsert(SListNode** plist, SListNode* pos, int x)
{
assert(*plist != NULL);
if (*plist == pos)//如果只有一个节点的话
{
SListNodePushFront(&plist, x);
}
SListNode* cur = *plist;
SListNode* prevcur = NULL;
while (cur != pos)
{
prevcur = cur;
cur = cur->next;
}
SListNode* newnode = BuyListNode(x);
newnode->next = pos;
prevcur->next = newnode;
}
int main()
{
//可以调用各种函数接口进行测试
SListNode* plist;
SListInitNode(&plist);
SListPushBack(&plist, 1);
SListPushBack(&plist, 1);
SListPrint(plist);
return 0;
}
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
当前标题:单链表实现c语言-创新互联
标题网址:http://pwwzsj.com/article/csjjpd.html