#include <stdio.h>
#include <stdlib.h>
//手撕链表
typedef int DateType;
typedef struct List
{
DateType val;
struct List* next;
}LT;
//返回新节点
LT* CreateBayNode(DateType x)
{
LT* newnode=(LT*)malloc(sizeof(LT));
if(newnode==NULL)
{
perror("newnode malloc fail");
return NULL;
}
newnode->next=NULL;
newnode->val=x;
return newnode;
}
//尾插
void PushBank(LT** head,DateType x)
{
//创建要插入的节点
LT* newnode = CreateBayNode(x);
//判断头节点是否为NULL
if(*head==NULL)
{
*head=newnode;
}
else
{
//进行找尾
LT* cur=*head;
LT* tail=*head;
while(cur)
{
tail=cur;
cur=cur->next;
}
//进行连接
tail->next=newnode;
}
}
//在pos位置后面插入
void PushPosBank(LT** head,int m)
{
LT*cur=*head;
LT* tail=*head;
int n=m;
while(cur && n--)
{
tail=cur;
cur=cur->next;
}
LT* next=tail->next;
LT* newnode=CreateBayNode(m);
tail->next=newnode;
newnode->next=next;
}
//打印
void ListPrint(LT* head)
{
LT* cur=head;
while(cur)
{
printf("%d ",cur->val);
cur=cur->next;
}
}
int main()
{
int n=0;
int m=0;
scanf("%d %d",&n,&m);
int arr[n];
for(int i=0;i<n;i++)
{
scanf("%d ",&arr[i]);
}
LT* A=NULL;
for(int i=0;i<n;i++)
{
PushBank(&A, arr[i]);
}
PushPosBank(&A,m);
ListPrint(A);
return 0;
}
将数组合成一个链表
随后用i生成一个新节点
并插入到pos位置的后面

京公网安备 11010502036488号