题解 | #牛牛的链表添加节点#
牛牛的链表添加节点
https://www.nowcoder.com/practice/e33b79c2e15a41f9b541e73cd256124a
#include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node* next; } Node; typedef struct list { Node* head; } List; void print(List* list); void add(int num, List* list); void add1(int i, List* list, int n); int main() { int n, i, num; List list; list.head = NULL; scanf("%d %d", &n, &i); for (int t = 0; t < n; t++) { scanf("%d", &num); add(num, &list); } add1(i, &list, n); print(&list); return 0; } void add(int num, List* list) { Node* p = (Node*)malloc(sizeof(Node)); p->data = num; p->next = NULL; Node* last = list->head; if (list->head) { while (last->next) { last = last->next; } last->next = p; } else { list->head = p; } } void add1(int i, List* list, int n) { if (i == 0) { Node* p = (Node*)malloc(sizeof(Node)); p->data = i; p->next = list->head; list->head = p; } else if (i == n) { Node* p = (Node*)malloc(sizeof(Node)); Node* last = list->head; while (last->next) { last = last->next; } p->data = i; last->next = p; } else { Node* pre = NULL; Node* cur = list->head; Node* p = (Node*)malloc(sizeof(Node)); p->data = i; for (int j = 0; j < i; j++) { pre = cur; cur = cur->next; } pre->next = p; p->next = cur; } } void print(List* list) { Node* p; for (p = list->head; p; p = p->next) { printf("%d ", p->data); } }