题解 | #牛牛的链表添加节点#
牛牛的链表添加节点
https://www.nowcoder.com/practice/e33b79c2e15a41f9b541e73cd256124a
#include <stdio.h>
#include <stdlib.h>
//链表结点的定义
struct Node {
int num;
struct Node* Next;
};
//创建头结点
struct Node* creatList() {
struct Node* headnode;
headnode = (struct Node*)malloc(sizeof(struct Node));
headnode->num = 0;
headnode->Next = NULL;
return headnode;
}
//创建结点
struct Node* creatnode(int num) {
struct Node* newnode;
newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->num = num;
newnode->Next = NULL;
return newnode;
}
int main() {
int n, num, i;
scanf("%d %d\n", &n, &i);
struct Node* L = creatList();
struct Node* q = L;
while (scanf("%d ", &num) != EOF) {
struct Node* p = creatnode(num);
//尾插法
q->Next = p;
q = p;
}
//找到第i个结点
q = L;
num = i;
while (i > 0) {
q = q->Next;
i--;
}
//创建值为i的结点并插入
struct Node* p = creatnode(num);
p->Next = q->Next;
q->Next = p;
for (struct Node* p = L->Next; p != NULL ; p = p->Next) {
printf("%d ", p->num);
}
return 0;
}
