题解 | #牛牛的书#
牛牛的书
https://www.nowcoder.com/practice/30bb969e117b4f6d934d4b60a2af7489
#include <stdio.h> #include <stdlib.h> struct node { char book[100]; int data; struct node *next; }; struct node *create_book(int n) { struct node *pnew=NULL; struct node *head=NULL; struct node *tail=NULL; for(int i=0;i<n;i++) { pnew=(struct node *)malloc(sizeof(*pnew)); pnew->next=NULL; int x; scanf("%s", pnew->book); scanf("%d", &x); pnew->data=x; if(head==NULL)//无中生有 { head=pnew; tail=pnew; } else//从少到多 { if(pnew->data<head->data)//头插 { pnew->next=head; head=pnew; } else if(pnew->data>tail->data)//尾插 { tail->next=pnew; tail=pnew; } else//插中间 { struct node *p=head; struct node *pre=NULL; while(p) { if(pnew->data<=p->data) { pre->next=pnew; pnew->next=p; break; } pre=p; p=p->next; } } } } return head; } void printf_book(struct node *h)//输出 { struct node *p=h; while(p) { printf("%s\n",p->book); p=p->next; } } int main() { int n; scanf("%d",&n); struct node *p=create_book(n); printf_book(p); return 0; }