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

单链表详解

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

单链表详解

文章目录

打印创建一个节点尾插头插头删尾删查找插入到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);
}

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

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

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