题解 | #牛牛的书#
牛牛的书
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;
}
查看8道真题和解析
智元机器人成长空间 174人发布
