c语言商品货架栈完整代码
时间: 2023-12-02 22:40:24 浏览: 63
以下是一个C语言商品货架栈的完整代码,其中包括了入栈、出栈、判断栈是否为空、判断栈是否已满等操作:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 100 // 定义栈的最大容量
typedef struct {
char name[20]; // 商品名称
float price; // 商品价格
} Goods;
typedef struct {
Goods sp[MAXSIZE]; // 栈的存储空间
int top; // 栈顶指针
} Stack;
// 初始化栈
void InitStack(Stack *s) {
s->top = -1;
}
// 判断栈是否为空
int IsEmpty(Stack *s) {
return s->top == -1;
}
// 判断栈是否已满
int IsFull(Stack *s) {
return s->top == MAXSIZE - 1;
}
// 入栈
int Push(Stack *s, Goods g) {
if (IsFull(s)) {
return 0;
}
s->top++;
strcpy(s->sp[s->top].name, g.name);
s->sp[s->top].price = g.price;
return 1;
}
// 出栈
int Pop(Stack *s, Goods *g) {
if (IsEmpty(s)) {
return 0;
}
strcpy(g->name, s->sp[s->top].name);
g->price = s->sp[s->top].price;
s->top--;
return 1;
}
int main() {
Stack s;
InitStack(&s);
Goods g1 = {"apple", 3.5};
Goods g2 = {"banana", 2.5};
Goods g3 = {"orange", 4.0};
Push(&s, g1);
Push(&s, g2);
Push(&s, g3);
Goods g;
while (Pop(&s, &g)) {
printf("商品名称:%s,价格:%f\n", g.name, g.price);
}
return 0;
}
```