题解 | #牛牛的链表删除#

牛牛的链表删除

https://www.nowcoder.com/practice/d3df844baa8a4c139e103ca1b1faae0f

#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 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, x;
    scanf("%d", &n);
    scanf("%d", &x);
    struct node* head = init_node(n);
    for (int i = 0; i < n; i++) {
        int var;
        scanf("%d", &var);
        push(head, var);
    }
    delete_by_data(head, x);
    print_list(head);
    if (head != NULL) {
        free(head);
        head = NULL;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
09-11 10:45
点赞 评论 收藏
分享
点赞 评论 收藏
分享
今天刚通知oc
跑不快的yyyf:接好运
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务