链表没有连续的数据,而是一个结点中有下一个节点的地址,所以在删除数据的时候,直接用free释放就行了。
链表主要操作的实现
void SListPrint(SLTNode* phead) //打印
{
SLTNode* cur = phead;
while (cur != NULL)
{
printf("%d->", cur->data);
cur = cur->next;
}
}
SLTNode* CreatListNode(SLTDataType x) //创建新节点
{
SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
if (newnode == NULL)
{
printf("malloc fail\n");
exit(-1);
}
newnode->data = x;
newnode->next = NULL;
return newnode;
}
void SListPushBack(SLTNode** pphead, SLTDataType x) //尾插
{
SLTNode* newnode = CreatListNode(x);
if (*pphead == NULL)
{
*pphead = newnode;
}
else
{
//找到尾节点
SLTNode* tail = *pphead;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = newnode;
}
}
void SListPushFront(SLTNode** pphead, SLTDataType x) //头插
{
SLTNode* newnode = CreatListNode(x);
newnode->next = *pphead;
*pphead = newnode;
}
void SListPopBack(SLTNode** pphead) //尾删
{
SLTNode* prev = NULL;
SLTNode* tail = *pphead;
while (tail->next)
{
prev = tail;
tail = tail->next;
}
free(tail);
tail = NULL;
prev->next = NULL;
}
void SListPopFront(SLTNode** pphead) //头删
{
assert(*pphead != NULL);
SLTNode* next = (*pphead)->next;
free(*pphead);
*pphead = next;
}
要改变链表数据的值话,需要传结构体指针地址过来,要用二级指针接收,从而改变它的值。
SLTNode* SListFind(SLTNode* phead, SLTDataType x)
{
SLTNode* cur = phead;
while (cur)
{
if (cur->data == x)
return cur;
else
cur = cur->next;
}
return NULL;
}
void SListInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
SLTNode* newnode = CreatListNode(x);
if (*pphead == pos)
{
newnode->next = *pphead;
*pphead = newnode;
}
//找到pos的前一个位置
SLTNode* posPrev = *pphead;
while (posPrev->next != pos)
{
posPrev = posPrev->next;
}
posPrev->next = newnode;
newnode->next = pos;
}
void SListErase(SLTNode** pphead, SLTNode* pos)
{
if (*pphead == pos)
{
SListPopFront(pphead);
}
else
{
SLTNode* prev = *pphead;
while (prev->next!=pos)
{
prev = prev->next;
}
prev->next = pos->next;
free(pos);
pos = NULL;
}
}
这些天一直是专注于知识的学习,不过今天,我发现这样的学习空洞真的挺大的,所以在下周我决定在知识和算法的学习上进行对半分,加强对算法的提升,争取多做题,同时在做题中也能学到新的知识。