1.使用二级指针版本:调用时,传入的是指针变量地址,需要改变指针的指向必须使用二级指针
//1.test.c
void TestSList()
{
SLTNode* plist = NULL;
SListPushBack(&plist, 1);
SListPushBack(&plist, 2);
SListPushBack(&plist, 3);
SListPushBack(&plist, 4);
SListPushBack(&plist, 5);
SListPushBack(&plist, 6);
SListPushBack(&plist, 7);
SListPrint(plist);
SListPushFront(&plist, 0);
SListPrint(plist);
}
int main()
{
TestSList5();
return 0;
}
//2.seqlist
#include "SList.h"
void SListPrint(SLTNode* phead)
{
SLTNode* cur = phead;
while (cur != NULL)
{
printf("%d->", cur->data);
cur = cur->next;
}
printf("NULLn");
}
SLTNode* BuySListNode(SLTDataType x)
{
SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
assert(newnode);
newnode->data = x;
newnode->next = NULL;
return newnode;
}
void SListPushBack(SLTNode** pphead, SLTDataType x)
{
SLTNode* newnode = BuySListNode(x);
if (*pphead == NULL)
{
*pphead = newnode;
}
else
{
// 找尾节点
SLTNode* tail = *pphead;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = newnode;
}
}
2.不使用二级指针
//1.test.c
SListNode*plist = BuySListNode(0);
SListNode*pplist = BuySListNode(0);
printf("%x",plist);//指针变量
printf("%x",&plist);//指针指向的内存地址
SListPushBack(plist,10);
plist->next = pplist;
SListPushBack(pplist,11);
pplist->next=NULL;
//2.seqplsit.c
SListNode* BuySListNode(SLTDateType x)
{
SListNode* ps = (SListNode*)malloc(sizeof(SListNode));
ps->data=x;
ps->next=NULL;
return ps;
}
void SListPrint(SListNode* plist)
{
SListNode* cur = plist;
while(cur!=NULL)
{
printf("%d ",cur->data);
cur = cur->next;
}
}
void SListPushBack(SListNode* pplist, SLTDateType x)
{
//SListNode*plist = BuySListNode(x);
SListNode* tail=pplist;
//找尾
while (tail->next != NULL)
{
tail = tail->next;
}
tail->data = x;
tail->next=NULL;
//}
}
上述比较可知:push_iback函数内部malloc内存,但是如果使用值传递,并不会修改实参的指向,类似如下博客:
关于链表初始化中为何使用二级指针(指向指针的指针)的对比解释 - GUPU_番茄呀 - 博客园
指针作为函数参数,可以使用指针来改变指向的值,但是不可以改变指针 的指向,想要修改指向,必须使用二级指针。见下文:
深入理解指针作为函数形参_宇智波藤原的博客-CSDN博客_指针作为函数形参
但是使用第一种,更加高大上一些,使用起来也比较方便,通过这样的对比可以更好理解二级指针



