打印创建一个节点尾插头插头删尾删查找插入到pos后删除pos位置后面的值
学习单链表一定要多画图
单链表的结构
void SLNPrint(SLN** pphead)
{
assert(pphead);
SLN* cur = *pphead;
while (cur != NULL)
{
printf("%d->", cur->data);
cur = cur->next;
}
printf("NULLn");
}
创建一个节点
SLN* BuySLNdata( SLNDataType x)
{
SLN* newnode = (SLN*)malloc(sizeof(SLN));
if (newnode == NULL)
{
printf("malloc失败n");
return 0;
}
else
{
newnode->data = x;
newnode->next = NULL;
return newnode;
}
}
尾插
尾插的时候,如果没有节点,直接将要插入的节点设置成头节点,
如果有多个节点,只需要向后面找到最后一个元素,然后插入就行
void SLNPushBack(SLN** pphead, SLNDataType x)
{
assert(pphead);
SLN* newnode = BuySLNdata(x);
if (*pphead == NULL)
{
*pphead = newnode;
}
else
{
SLN* cur = *pphead;
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next = newnode;
}
}
头插
如果没有节点,直接将要头插的节点赋值给*pphead就行
如果有节点,将要头插的节点指向头,然后赋值给头就行
void SLNPushFront(SLN** pphead, SLNDataType x)
{
assert(pphead);
SLN* newnode = BuySLNdata(x);
//没有节点的情况
if (*pphead == NULL)
{
*pphead = newnode;
}
else
{
newnode->next = *pphead;
*pphead = newnode;
}
}
头删
需要判断三种情况:1没有节点,2一个节点,3多个节点
void SLNPopFront(SLN** pphead)
{
//没有节点
//只有一个节点
if (*pphead == NULL)
{
return;
}
else if ((*pphead)->next == NULL)
{
free(*pphead);
*pphead = NULL;
}
else
{
SLN* newnode = *pphead;
*pphead = (*pphead)->next;
free(newnode);
}
}
尾删
要判断3种情况:1没节点,2有一个节点,3多个节点
void SLNPopBack(SLN** pphead)
{
assert(pphead);
if (*pphead == NULL)
{
return;
}
else if((*pphead)->next==NULL)
{
free(*pphead);
*pphead = NULL;
}
else
{
SLN* cur = *pphead;
SLN* pre = NULL;
while (cur->next != NULL)
{
pre = cur;
cur = cur->next;
}
free(cur);
pre->next = NULL;
}
}
查找
SLN* SLNFind(SLN** pphead, SLNDataType x)
{
assert(pphead);
SLN* cur = *pphead;
while (cur->data != x)
{
cur = cur->next;
}
return cur;
}
插入到pos后
void SLNInsertAfter(SLN** pphead, SLN* pos, SLNDataType x)
{
assert(pphead && pos);
SLN* newnode = BuySLNdata(x);
SLN* cur = *pphead;
if (*pphead == pos)
{
SLNPushBack(pphead, x);
}
else
{
while (cur != pos)
{
cur = cur->next;
}
newnode->next = cur->next;
cur->next = newnode;
}
}
删除pos位置后面的值
void SLNEraseAfter(SLN** pphead, SLN* pos)
{
assert(pphead && pos);
if (pos->next == NULL)
return;
SLN* cur = pos->next;
pos->next = cur->next;
free(cur);
}



