练习4-4 在栈操作中添加几个命令,分别用于在不弹出元素的情况下打印栈顶元素;复制栈顶元素;交换栈顶两个元素的值。另外增加一个命令用于清空栈。
最后添加一个简单测试。
#include <stdio.h>
#define MAXVAL 100
int sp = 0;
double val[MAXVAL];
void push(double f)
{
if (sp < MAXVAL)
val[sp++] = f;
else
printf("error: stack full, can't push %g\n", f);
return;
}
double pop(void)
{
if (sp > 0)
return val[--sp];
else
{
printf("error:stack empty\n");
return 0.0;
}
}
void print_no_pop(void)
{
if (sp > 0)
printf("%g\n", val[sp-1]);
else
printf("error:stack empty\n");
return;
}
void stack_top_cpy(void)
{
if (sp > 0 || sp < MAXVAL)
val[sp++] = val[sp-1];
else if (sp <= 0)
printf("error:stack empty\n");
else
printf("error:stack full\n");
return ;
}
void swap_stack_top(void)
{
double temp;
if (sp >= 2)
{
temp = val[sp-1];
val[sp-1] = val[sp-2];
val[sp-2] = temp;
}
else
printf("not enough number\n");
return;
}
void empty_stack(void)
{
sp = 0;
return;
}
int main()
{
double i;
for (i = 1.0; i < 20.0; i++)
push(i);
printf("affirm:%g\n", pop());
swap_stack_top();
printf("swap:%g\n", pop());
printf("swap:%g\n", pop());
stack_top_cpy();
printf("copy:%g\n", pop());
printf("copy:%g\n", pop());
printf("print_no_pop:\n");
print_no_pop();
empty_stack();
printf("empty:%g\n", pop());
return 0;
}