题解 | #牛牛的书#

牛牛的书

https://www.nowcoder.com/practice/30bb969e117b4f6d934d4b60a2af7489

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

typedef struct Node {
    char name[100];
    int price;
    struct Node* next;
} Node;

Node* createNode(char* name, int price) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    strcpy(newNode->name, name);
    newNode->price = price;
    newNode->next = NULL;
    return newNode;
}

void insertNode(Node** head, char* name, int price) {
    Node* newNode = createNode(name, price);

    if (*head == NULL || price < (*head)->price) {
        newNode->next = *head;
        *head = newNode;
    } else {
        Node* current = *head;
        while (current->next != NULL && price >= current->next->price) {
            current = current->next;
        }
        newNode->next = current->next;
        current->next = newNode;
    }
}

void printList(Node* head) {
    while (head != NULL) {
        printf("%s\n", head->name);
        head = head->next;
    }
}

void freeList(Node* head) {
    while (head != NULL) {
        Node* temp = head;
        head = head->next;
        free(temp);
    }
}

int main() {
    int n;
    scanf("%d", &n);
    Node* head = NULL;
    for (int i = 0; i < n; i++) {
        char name[100];
        int price;
        scanf("%s %d", name, &price);
        insertNode(&head, name, price);
    }
    printList(head);
    freeList(head);
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务