该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
大佬们 怎么用C语言实现栈啊
怎么能让栈display的时候保留栈的元素
#include "stack.h"
#include
#include
int main() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
double val;
CreateStack(stack, 5);
Push(stack, 5);
Push(stack, 6.5);
Push(stack, -3);
Push(stack, -8);
DisplayStack(stack);
if (Top(stack, &val))
printf("Top: %.2f\n", val);
Pop(stack, &val);
if (Top(stack, &val))
printf("Top: %.2f\n", val);
while (!IsEmpty(stack))
Pop(stack, &val);
DisplayStack(stack);
Push(stack, 5);
DisplayStack(stack);
DestroyStack(&stack);
DisplayStack(stack);
}
bool CreateStack(Stack* stack, int size)
{
if (size <= 0)
return false;
stack->values = (double*)malloc(sizeof(double) * size);
stack->top = -1;
stack->maxTop = size - 1;
return true;
}
bool IsEmpty(Stack* stack)
{
if (stack->top != 0)
return false;
else
return true;
}
bool IsFull(Stack* stack)
{
if (stack->top == stack->maxTop - 1)
return true;
else
return false;
}
bool Top(Stack* stack, double* x)
{
if (IsEmpty(stack))
return false;
else
*x = stack->values[stack->top];
return true;
}
bool Push(Stack* stack, double x)
{
if (IsFull(stack))
return false;
else
stack->values[++stack->top] = x;
return true;
}
bool Pop(Stack* stack, double* x)
{
if (IsEmpty(stack))
return false;
else
*x = stack->top--;
return true;
}
void DisplayStack(Stack* stack)
{
while (!IsEmpty(stack)) {
printf("%lf\n", stack->values[stack->top--]);
}
return ;
}
void DestroyStack(Stack** pstack)
{
if (IsEmpty(*pstack))
return;
else
free(pstack);
return;
}