题解 | #牛牛的链表添加节点#
牛牛的链表添加节点
https://www.nowcoder.com/practice/e33b79c2e15a41f9b541e73cd256124a
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int num;
struct node* next;
} Node;
Node* createlist(int num) {
Node* head = (Node*)malloc(sizeof(Node));
head->num = num;
head->next = NULL;
return head;
}
void add_node(Node* head, int num) {
Node* p = (Node*)malloc(sizeof(Node));
p->num = num;
p->next = NULL;
Node* q = head;
while (q->next) {
q = q->next;
}
q->next = p;
}
void Printlist(Node* cur) {
while (cur) {
printf("%d ", cur->num);
cur = cur->next;
}
}
Node* insert(Node* head,int n,int num)
{
Node* p=head;
n-=1;
while(n--)
{
p=p->next;
}
Node* q=malloc(sizeof(Node));
q->num=num;
q->next=p->next;
p->next=q;
return head;
}
int main() {
int n, i;
scanf("%d%d", &n, &i);
int a;
scanf("%d", &a);
Node* head = createlist(a);
for (int j = 1; j < n; j++) {
scanf("%d", &a);
add_node(head, a);
}
head=insert(head, i, i);
Printlist(head);
return 0;
}
查看18道真题和解析