利用栈与队列解决问题(商品货架管理)

#include <cstdio>

#include <cstdlib>

#include <cstring>

#define maxsize 100

typedef int Status;

typedef struct Elem{

char name[50] = { '\0' };

char data[30] = { '\0' };

}ElemType;

typedef struct {

ElemType* base;

ElemType* top;

int stacksize;

}SqStack;

Status InitStack(SqStack& S) {//初始化栈

S.base = (ElemType*)malloc(maxsize * sizeof(ElemType));

if (!S.base) return 0;

S.top = S.base;

S.stacksize = maxsize;

}

Status Push(SqStack& S, ElemType e) {//入栈

if (S.top - S.base == S.stacksize) return 0;

*(S.top++) = e;

return 1;

}

Status Pop(SqStack& S, ElemType& e) {//出栈

if (S.top == S.base) return 0;

e = *(--S.top);

return 1;

}

void Purchase_Product_noEmpty(SqStack& S, SqStack& S1,int num,ElemType m) {//货架不为空时进货

InitStack(S1);

ElemType e;

printf("请输入商品名:");

scanf("%s", m.name, 30);

printf("请输入商品的生产日期:");

scanf("%s", m.data, 20);

printf("请输入商品数:");

scanf("%d", &num);

while (Pop(S,e)) {//放入周转货架

Push(S1, e);

}

while (num--) {//新商品入周转货架

if (Push(S1, m) == 0) {

printf("周转货架已满,请选用更大的周转货架!\n");

return;

}

}

while (Pop(S1, e)) {//周转货架入原货架

if (Push(S, e) == 0) {

printf("原货架已满,请选用更大的原货架!\n");

return;

}

}

printf("进货成功!\n");

}

void Inquire_Number(SqStack S) {//展示当前货架商品

printf("商品数:%d\n", S.top - S.base);

while (S.top != S.base) {

S.top--;

printf("%s\t\t\t\t%s\n", S.top->name,S.top->data);

}

}

void Purchase_Product_Empty(SqStack& S,ElemType e,int num) {//货架为空时进货

printf("请输入商品的名称:");

scanf("%s", e.name,30);

printf("请输入商品的生产日期:");

scanf("%s", e.data, 20);

printf("请输入商品数:");

scanf("%d", &num);

while (num--) {

if (Push(S, e) == 0) {

printf("货架已满,请更换更大的货架!\n");

return;

}

}

printf("进货成功!\n");

}

int main() {

SqStack S, S1;//原货架与周转货架

int k,m=0,n=0;

ElemType a, b, c;

InitStack(S);

printf("请选择你要进行的操作\n1.进货\n2.查询商品数\n3.结束\n\n");

while (scanf("%d", &k) != EOF) {

switch (k) {

case 1:

if (S.top == S.base) {//货架为空

Purchase_Product_Empty(S, a, m);

}

else {

Purchase_Product_noEmpty(S, S1, n, b);

}

break;

case 2:

printf("---------------------\n");

Inquire_Number(S);

break;

case 3:

return 0;

}

printf("---------------------\n\n\n");

printf("请选择你要进行的操作\n1.进货\n2.查询商品数\n3.结束\n\n");

}

}

  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值