书籍录入(链表有序插入)

9 篇文章 0 订阅
9 篇文章 0 订阅

图书店营业员要通过程序录入书籍信息, 包括录入书籍名称、价格;当输入的书籍名称是"##"时,表示结束录入。

现要求使用链表编程,编写函数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;;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值