题解 | #牛牛的链表添加节点#
牛牛的链表添加节点
https://www.nowcoder.com/practice/e33b79c2e15a41f9b541e73cd256124a
#include <stdio.h>
#include<malloc.h>
struct Node //创建结点结构
{
int data;
struct Node* pNext;
};
struct Node* Creat_List(int* pArr,int len) //数组转换存储为链表
{
int i;
struct Node* pHead = (struct Node*)malloc(sizeof(struct Node));
pHead->pNext = NULL;
struct Node* pTail = pHead;
for(i=0;i<len;i++)
{
struct Node* pNew = (struct Node*)malloc(sizeof(struct Node));
pNew->data = pArr[i];
pNew->pNext = NULL;
pTail->pNext = pNew;
pTail = pNew;
}
return pHead;
}
void Traverse_List(struct Node* pHead) //遍历打印链表
{
struct Node* p = pHead->pNext;
while(p->pNext != NULL)
{
printf("%d ",p->data);
p = p->pNext;
}
printf("%d",p->data);
}
void AddDote(struct Node* pHead,int num) //定义函数增加结点
{
struct Node* p = pHead->pNext,*p1 = p->pNext; //p是目标结点,p1是首结点后面的第一个结点,p跟p1后面会用循环一直推进
int count = 1; //定义计数的整型数字变量为1,后面循环推进
while(1) //一直循环!!!
{
if(count == num) //当计数的数字推进到目标数字时,进行插入新结点操作
{
struct Node* pNew = (struct Node*)malloc(sizeof(struct Node));
pNew->data = count; //给新结点数值域赋值
p->pNext = pNew; //插入新结点
pNew->pNext = p1; //新结点的下一个结点定义为原先目标结点后面第一个结点
break; //完成结点增加操作后 跳出循环!!!
}
p = p->pNext; //循环推进
p1 = p1->pNext; //循环推进
count++; //计数的数字推进
}
}
int main()
{
int len,i,adnum;
scanf("%d",&len);
scanf("%d",&adnum);
int* pArr = (int*)malloc(len*sizeof(int));
for(i=0; i<len; i++)
{
scanf("%d",&pArr[i]);
}
struct Node* pHead = Creat_List(pArr, len);
AddDote(pHead, adnum);
Traverse_List(pHead);
}
查看17道真题和解析
