数据结构之SWUSTOJ952: 单链表的插入操作的实现

题目:

解题思路:

如果对指针掌握得不好的建议可以看看下面两篇文章,找找灵感:

C语言进阶指针详解完整版(数组指针,指针数组的辨析,函数指针)_YRedd22的博客-CSDN博客https://blog.csdn.net/weixin_56054625/article/details/122633094?spm=1001.2014.3001.5502数据结构之链表-2022-3-6_YRedd22的博客-CSDN博客https://blog.csdn.net/weixin_56054625/article/details/123310468?spm=1001.2014.3001.5502

代码:

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct SListNode
{
	int data;
	struct SListNode* next;
}SL;
//要改变指针的指向需要传参传二级指针
void HeadNodeInit(SL** plist)
{
	*plist = (SL*)malloc(sizeof(SL));
	(*plist)->next = NULL;
	//哨兵位头结点是不存储有效数据的
}//初始化哨兵位头结点
void SLCreate(SL** plist,int n)
{
	int x = 0;
	SL* cur = *plist;
	while (n > 0)
	{
		SL* newnode = (SL*)malloc(sizeof(SL));
		scanf("%d", &x);
		newnode->data = x;
		cur->next = newnode;
		cur = newnode;
		n--;
	}
	cur->next = NULL;//最后记得把尾节点置空
}
bool SLInsert(SL** plist, int i, int dat)
{
	if (i <= 0)
		return false;
	SL* cur = *plist;
	int j = 0;//记录头节点的位置
	while (cur != NULL && j < i - 1)//当cur为空是结束或者找到i节点结束
	{
		j++;
		cur = cur->next;
	}
	if (cur == NULL)
		return false;
	SL* newnode = (SL*)malloc(sizeof(SL));
	newnode->data = dat;
	newnode->next = cur->next;
	cur->next = newnode;
	return true;
}
void SLPrint(SL** plist)
{
	SL* cur = (*plist)->next;
	while(cur)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
}
int main()
{
	SL* plist=NULL;
	HeadNodeInit(&plist);//注意传二级指针改变指针的指向
	int n = 0;
	scanf("%d", &n);
	getchar();
	SLCreate(&plist, n);
	int i = 0;
	int dat = 0;
	scanf("%d", &i);
	getchar();
	scanf("%d", &dat);
	getchar();
	bool b = SLInsert(&plist, i, dat);
	if (b == false)
		printf("error!");
	else
		SLPrint(&plist);
	return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

~|Bernard|

你的鼓励是我写下去最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值