题解 | #【模板】链表#

【模板】链表

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;
}

全部评论

相关推荐

爱看电影的杨桃allin春招:我感觉你在炫耀
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务