phead只是一个拷贝,他变了,原主不会变哦!
在链表尾插中犯的错:
void SListPushBack(SLTNode* phead, SLTDateType x)//链表尾插
{
SListNode* newnode = (SListNode*)malloc(sizeof(SListNode)); //node是节点的意思;
newnode->data = x;
newnode->next = NULL;
if (phead==NULL)
{
phead = newnode;
}
else
{
SListNode* tail = phead;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = newnode;
}
}
程序在第九行出错,原因如下:
phead是一个指针,他用来储存传入函数的指针所存的地址(结构体的地址);在程序运行到第九行的时候,phead存的地址被覆盖为newnode所存的地址,此时传入函数的那个指针所存的地址并没有改变,运行了函数,但是什么都没有改变。
解决方法:
void SListPushBack2(SLTNode** phead, SLTDateType x)//链表尾插
{
SListNode* newnode = (SListNode*)malloc(sizeof(SListNode)); //node是节点的意思;
newnode->data = x;
newnode->next = NULL;
if (*phead == NULL)
{
*phead = newnode;
}
else
{
SListNode*tail = *phead;
while (tail->next != NULL)
{
tail = tail->next;
}
(*tail).next = newnode;//跟 tail->next=newnode 一样的效果
}
}
总结:
在函数中,你要改变int,就传int*,你要改变int *就传int**;
最后通过解引用去完成改变。