问答题
[说明]
以下程序的功能是实现堆栈的一些基本操作。堆栈类stack共有三个成员函数:empty判断堆栈是否为空;push进行人栈操作;pop进行出栈操作。
[C++程序]
#include "stdafx. h"
#include <iostream, h>
eonst int maxsize = 6;
class stack {
float data[ maxsize];
int top;
public:
stuck(void);
~ stack(void);
bool empty(void);
void push(float a);
float pop(void);
};
stack: :stack(void)
{ top =0;
cout < < "stack initialized." < < endl;
}
stack:: ~stack(void) {
cout < <" stack destoryed." < < endl;
bool stack:: empty (void) {
return{{U}} (1) {{/U}};
void stack: :push(float a)
if(top= =maxsize) {
cout < < "Stack is full!" < < endl;
return;
data[top] =a;
{{U}}(2) {{/U}};
}
float stack:: pop (void)
{ if({{U}} (3) {{/U}}){
cout< < "Stack is undcrflow !" < < endl;
return 0;
{{U}}(4) {{/U}};
return{{U}} (5) {{/U}};
}
void main( )
{ stack s;
coat < < "now push the data:";
for(inti=l;i< =maxsize;i+ +) {
cout< <i< <" ";
s. push(i);
}
coat < < endl;
cout< < "now pop the data:";
for(i = 1 ;i < = maxsize ;i + + )
cout< <s. pop()< <" ";
}
【正确答案】
【答案解析】(1)top==0? true:false (2)top++(或者top =top+1)(3)top==0 (4)top--(或者top =top-1)
(5)data[top]
判断堆栈是否为空的条件是top为0,而且本函数的返回值为布尔类型,故此处应该填写top==0? true:false;
(2)数据入栈后,栈顶指针要向上移动一个单元;
(3)top为0说明堆栈已经空了,此处if语句返回堆栈为空的提示;
(4)先将栈顶指针往下移动一个单元,才可以指向要出栈的数据;
(5)本行代码的功能是返回要出栈的数据。