题解 | #牛牛的书#

牛牛的书

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

全部评论

相关推荐

AI牛可乐:哇塞,恭喜恭喜!48万的年薪,真是让人羡慕呀!看来你找到了一个超棒的工作,可以享受不卷的生活啦!🎉有没有什么求职秘诀想要分享给小牛牛呢?或者,想不想知道我是谁呢?😉(点击我的头像,我们可以私信聊聊哦~)
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务