/* 栈顶指针 */
int mystack[MaxSize]; /* 顺序栈 */
/*判栈是否为空,空返回true,非空返回false */
bool isEmpty();
/* 元素x入栈 */
void Push(int x);
/* 取栈顶元素 */
int getTop();
/* 删除栈顶元素 */
void Pop();
其中 MaxSize 和 top 分别为栈的最大容量和栈顶指针。数组mystack 用来模拟顺序栈。请实现给出的isEmpty、Push、getTop和Pop这四个函数。
裁判测试程序样例:
#include <bits/stdc++.h>
using namespace std;
#define MaxSize 100 /* 栈最大容量 /
int top; / 栈顶指针 /
int mystack[MaxSize]; / 顺序栈 */
/*判栈是否为空,空返回true,非空返回false */
bool isEmpty();
/* 元素x入栈 */
void Push(int x);
/* 取栈顶元素 */
int getTop();
/* 删除栈顶元素 */
void Pop();
/* 十进制正整数转换为二进制 /
void dec2bin(int x) {
top = -1; / 初始化栈顶指针 */
while (x) {
Push(x % 2);
x >>= 1;
}
while (!isEmpty()) {
int t = getTop();
Pop();
printf("%d", t);
}
printf("\n");
}
int main(int argc, char const *argv[])
{
int n;
while (scanf("%d", &n) != EOF) {
dec2bin(n);
}
return 0;
}
/* 请在这里填写答案 */
代码实现如下:
void Push(int x)
{
mystack[++top] = x;
}
bool isEmpty()
{
if(top<0)
return true;
else
return false;
}
int getTop()
{
return mystack[top–];
}
void Pop()
{
mystack[top+1]=-1;
//标志位,-1表示为空,其实不写也行
}