每日一题Day19

基于链式存储结构的图书信息表的旧图书的出库

描述

定义一个包含图书信息(书号、书名、价格)的链表,读入相应的图书数据来完成图书信息表的创建,然后根据指定的待出库的旧图书的位置,将该图书从图书表中删除,最后输出该图书出库后的所有图书的信息。

输入

总计n+2行。首先输入n+1行,其中,第一行是图书数目n,后n行是n本图书的信息(书号、书名、价格),每本图书信息占一行,书号、书名、价格用空格分隔,价格之后没有空格。其中书号和书名为字符串类型,价格为浮点数类型。之后输入第n+2行,内容仅为一个整数,代表待删除的旧图书的位置序号。

输出

若删除成功:

输出旧图书出库后所有图书的信息(书号、书名、价格),总计n-1行,每行是一本图书的信息,书号、书名、价格用空格分隔。其中价格输出保留两位小数。

若删除失败:

只输出以下一行提示:抱歉,出库位置非法!

样例输入1 

8
9787302257646 Data-Structure 35.00
9787302164340 Operating-System 50.00
9787302219972 Software-Engineer 32.00
9787302203513 Database-Principles 36.00
9787810827430 Discrete-Mathematics 36.00
9787302257800 Data-Structure 62.00
9787811234923 Compiler-Principles 62.00
9787822234110 The-C-Programming-Language 38.00
2

样例输出1

9787302257646 Data-Structure 35.00
9787302219972 Software-Engineer 32.00
9787302203513 Database-Principles 36.00
9787810827430 Discrete-Mathematics 36.00
9787302257800 Data-Structure 62.00
9787811234923 Compiler-Principles 62.00
9787822234110 The-C-Programming-Language 38.00

解答:尾插法建立链表,根据给定位置找到删除元素的前驱,删除元素的前驱指向删除元素的后继。释放删除元素空间。

#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
	long long int num;
	char name[50];
	double price;
	struct node *next;
} Book,*BookList;

int main()
{
	int n;
	scanf("%d",&n);
	BookList L;
	Book *p,*q,*rear;
	L = (Book *)malloc(sizeof(Book));
	L->num=n;
	L->next=NULL;
	rear = L;
	while(n--)
	{
		p=(Book *)malloc(sizeof(Book));
		scanf("%lld %s %lf",&p->num,p->name,&p->price);
		rear->next = p;
		rear = p;
	}
	rear->next = NULL;
	int index;
	scanf("%d",&index);
	if(index>=1&&index<=L->num)
	{
		p=L;
		index--;
		while(index--)
		{
			p=p->next;
		}
		q=p->next;
		p->next=q->next;
		L->num--;
		free(q);
	}
	else
	{
		printf("Sorry, the storage location is illegal!\n");
		return 0;
	}
	p=L->next;
	while(p)
	{
		printf("%lld %s %.2f\n",p->num,p->name,p->price);
		p=p->next;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ZLambert/article/details/81542690