题解 | 牛牛的链表添加节点
牛牛的链表添加节点
https://www.nowcoder.com/practice/e33b79c2e15a41f9b541e73cd256124a
#include <stdio.h>
#include <stdlib.h>
#define N 100
struct Node
{
int data;
struct Node *next;
};
struct Node* createList(int *arr,int n)
{
struct Node *head = NULL, *tail = NULL;
for(int i = 0; i < n; i++)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = arr[i];
newNode -> next = NULL;
if(head == NULL)
{
head = newNode;
tail = newNode;
}
else
{
tail -> next = newNode;
tail = newNode;
}
}
return head;
}
void addNode(struct Node *head,int index)
{
struct Node *p = head;
int count = 1;//记录当前是第几个节点;
//找到插入节点的前一个节点
while (p != NULL && count < index)
{
p = p -> next;
count++;
}
if(p != NULL)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = index;
newNode -> next = p -> next;
p -> next = newNode;
}
}
void printList(struct Node *head)
{
struct Node *p = head;
while(p != NULL)
{
printf("%d ",p -> data);
p = p -> next;
}
}
int main()
{
int n,index;
scanf("%d %d",&n,&index);
int arr[N];
for(int i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
struct Node *head = createList(arr,n);
addNode(head,index);
printList(head);
return 0;
}
