题解 | #牛牛的链表添加节点#
牛牛的链表添加节点
https://www.nowcoder.com/practice/e33b79c2e15a41f9b541e73cd256124a
#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node* next; } Node; Node* creatList() { Node* head = (Node*)malloc(sizeof(Node)); head->next = NULL; return head; } void addNode(Node* head, int data) { Node* p = head; Node* q = (Node*)malloc(sizeof(Node)); while (p->next != NULL) { p = p->next; } q->data = data; p->next = q; q->next = NULL; } void addi(Node* head, int data) { Node* p = head; Node* q = (Node*)malloc(sizeof(Node)); for (int i = 0; i < data; i++) { p = p->next; } q->data = data; q->next = p->next; p->next = q; } void print(Node* head) { Node* p = head->next; while (p != NULL) { printf("%d ", p->data); p = p->next; } } int main() { Node* head = creatList(); int n, x; scanf("%d%d", &n, &x); for (int i = 0; i < n; i++) { int a; scanf("%d", &a); addNode(head, a); } addi(head, x); print(head); return 0; }