题目:
解题思路:
如果对指针掌握得不好的建议可以看看下面两篇文章,找找灵感:
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;
}