题解 | #牛牛的链表添加节点#
牛牛的链表添加节点
https://www.nowcoder.com/practice/e33b79c2e15a41f9b541e73cd256124a
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* init_node(int data) {
struct node* head = (struct node*)malloc(sizeof(struct node));
head->data = data;
head->next = NULL;
return head;
}
void push(struct node* head, int data) {
struct node* new_node = init_node(data);
struct node* p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = new_node;
}
// void swap(struct node* head, int x, int y) {
// if (head->data < x || head->data < y || x == y) {
// return;
// }
// struct node* p = head, *q = head;
// for (int i = 0; i < x; i++) {
// p = p->next;
// }
// for (int i = 0; i < y; i++) {
// q = q->next;
// }
// int temp = p->data;
// p->data = q->data;
// q->data = temp;
// }
// void delete_by_data(struct node* head, int data) {
// if (head->data == 0) {
// return;
// }
// struct node* p = head;
// while (p->next != NULL) {
// if (p->next->data == data) {
// struct node* q = p->next;
// p->next = p->next->next;
// free(q);
// continue;
// }
// p = p->next;
// }
// }
void insert_after_i(struct node* head, int i){
if (head->data<i) {
return;
}
if(head->data == i){
push(head, i);
return;
}
struct node* p = head;
for (int j=0;j<i;j++){
p = p->next;
}
struct node* new_node = init_node(i);
new_node->next = p->next;
p->next = new_node;
}
void print_list(struct node* head) {
if (head->data == 0) {
return;
}
struct node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
}
int main() {
int n, i;
scanf("%d", &n);
scanf("%d", &i);
struct node* head = init_node(n);
for (int i = 0; i < n; i++) {
int var;
scanf("%d", &var);
push(head, var);
}
insert_after_i(head, i);
print_list(head);
if (head != NULL) {
free(head);
head = NULL;
}
}

查看5道真题和解析
