题解 | #【模板】链表#

【模板】链表

https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 定义链表节点结构体
struct Node {
    int data;
    struct Node* next;
};
typedef struct Node Node;

// 插入节点
void insert(Node** head, int x, int y) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = y;
    newNode->next = NULL;

    if (*head == NULL) {
        *head = newNode;
        return;
    }

    Node* current = *head;
    Node* prev = NULL;

    while (current != NULL && current->data != x) {
        prev = current;
        current = current->next;
    }

    if (current == NULL) {
        prev->next = newNode;
    } else {
        if (prev != NULL) {
            prev->next = newNode;
        } else {
            newNode->next = *head;
            *head = newNode;
        }
        newNode->next = current;
    }
}

// 删除节点
void delete(Node** head, int x) {
    Node* current = *head;
    Node* prev = NULL;

    while (current != NULL && current->data != x) {
        prev = current;
        current = current->next;
    }

    if (current != NULL) {
        if (prev != NULL) {
            prev->next = current->next;
        } else {
            *head = current->next;
        }
        free(current);
    }
}

// 输出链表
void printList(Node* head) {
    if (head == NULL) {
        printf("NULL\n");
        return;
    }

    while (head != NULL) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

int main() {
    Node* head = NULL;

    int n;
    scanf("%d", &n);

    while (n--) {
        char operation[10];
        int x, y;
        scanf("%s", operation);

        if (strcmp(operation, "insert") == 0) {
            scanf("%d %d", &x, &y);
            insert(&head, x, y);
        } else if (strcmp(operation, "delete") == 0) {
            scanf("%d", &x);
            delete(&head, x);
        }
    }

    printList(head);
    return 0;
}

全部评论

相关推荐

Java抽象带篮子:难蚌,点进图片上面就是我的大头😆
点赞 评论 收藏
分享
点赞 评论 收藏
分享
昨天 13:08
蚌埠坦克学院 C++
服从性笔试吗,发这么多笔,现在还在发。
蟑螂恶霸zZ:傻 x 公司,发两次笔试,两次部门匹配挂,
投递金山WPS等公司10个岗位 >
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务