题解 | #牛牛的链表添加节点#
牛牛的链表添加节点
https://www.nowcoder.com/practice/e33b79c2e15a41f9b541e73cd256124a
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node* next;
} node;
//头结点
node* creatnode(int val){
node *p = (node*)malloc(sizeof(node));
if(p == NULL)
{
return NULL;
}
p->data = val;
p->next = NULL;
return p;
}
//插入节点
void insertnode(node* p, int val){
node * q = (node*)malloc(sizeof(node));
if(q == NULL){
return;
}
q->data = val;
q->next = NULL;
// node* tmp = p->next;
// while(tmp != NULL){
// tmp = tmp->next;
// }
p->next = q;
}
//打印
void printfnode(node* p){
node* head = p;
while(head->next != NULL){
printf("%d ",head->data);
head = head->next;
}
}
//插入节点
void istnode(node* p, int num){
node* head = p;
node* new = (node*)malloc(sizeof(node));
// while()
for(int i=1;i<num; i++)
head = head->next;
new->data = num;
new->next = head->next;
head->next = new;
}
// void istnode(node* p, int num){
// node *head = p;
// for(int i=0;i<num;i++){
// head = head->next;
// }
// }
int main() {
// int a, b;
// while (scanf("%d %d", &a, &b) != EOF) { // 注意 while 处理多个 case
// // 64 位输出请用 printf("%lld") to
// printf("%d\n", a + b);
// }
int a, b;
scanf("%d %d", &a, &b);
node* head = creatnode(0);
int *arr = (int*)malloc(sizeof(int)*a);
for(int i=0; i<a;i++){
scanf("%d",&arr[i]);
// insertnode(head, num);
}
head->data = arr[0];
node *p = head;
for(int j=1;j<=a;j++){
insertnode(p, arr[j]);
p = p->next;
}
istnode(head, b);
printfnode(head);
return 0;
}
#悬赏#