图书店营业员要通过程序录入书籍信息, 包括录入书籍名称、价格;当输入的书籍名称是"##"时,表示结束录入。
现要求使用链表编程,编写函数insert(),将营业员输入的所有书籍插入到链表中,要求插入链表时按书名字典序升序排序;
输入样例:
cprogramming 29
c++programm 89
visualbasic 28
software 32
testing 827
## 78
输出样例:
c++programm 89.00
cprogramming 29.00
software 32.00
testing 827.00
visualbasic 28.00
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct book
{
char name[40];
float price;
struct book *next;
};
struct book *insert(struct book *list, char name[40], float price)
{
struct book *head,*pnew;
pnew = (struct book *)malloc(sizeof(struct book));
strcpy(pnew -> name, name);
pnew -> price = price;
pnew -> next = NULL;
head = list;
//如果原链表为空,返回新创建的链表
if(head == NULL)
{
return pnew;
}//while
//如果原链表非空,进行插入
if(head != NULL && strcmp(head -> name, pnew -> name) > 0)//如果新节点小于头节点
{//插入在头节点前
pnew -> next = head;
head = pnew;
return head;
}//if
//插入在中间
struct book *pold, *p;
pold = head;
p = head -> next;
while(p != NULL)
{//查找插入位置,直到p节点大于新节点
if(strcmp(pnew -> name, p -> name) > 0)
{//往后移
pold = p;
p = p -> next;
}//if
else
{//进行插入
pnew -> next = p;
pold -> next = pnew;
return head;
}//else
}//while
//插入在最后
if(p == NULL)
{
pold -> next = pnew;//pold始终指向最后一个节点,因为如果在上一个 while 循环里没有找到插入点,则 pold 指向最后一个节点
return head;
}//if
}
/* 输出链表 */
void print(struct book *head){
struct book *pnode = head;
while(pnode != NULL)
{
printf("%s %.2f\n", pnode->name, pnode->price);
pnode = pnode->next;
}//while
}//print
int main()
{
struct book *list=NULL;
char name[40] = {0};
float price = 0;
while(1)
{
scanf("%s %f", name, &price);
if(strcmp(name, "##") == 0)
{
break;
}//if
list = insert(list, name, price);
}//while
print(list);
return 0;;
}