栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

单链表头插尾插必须使用二级指针码?

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

单链表头插尾插必须使用二级指针码?

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博客_指针作为函数形参 

但是使用第一种,更加高大上一些,使用起来也比较方便,通过这样的对比可以更好理解二级指针

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/861971.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号