问答题 请使用VC6或使用【答题】菜单打开考生文件夹proj2下的工程proj2,该工程中含有一个源程序文件proj2.cpp,请将堆栈类的定义补充完整。使程序的输出结果为: The element of stack are:4 3 2 1 注意:请勿修改主函数main和其他函数中的任何内容,只在横线处编写适当代码,不要改动程序中的其他内容,也不要删除或移动“//****found****”。//proj2.cpp#include<iostream>us ing namespace std;const int Size=5;class Stack;class Itern{public://**********found**********Item(const int&val):_____________;)//构造函数 对item进行初始化private: int item; Item*next; friend class Stack; }; class Stack { public: Stack():top(NULL){} 一Stack(); int Pop(); void Push(const int&);private: Item*top; }; Stack::一Stack() { Item*P=top,*q; while(P!=NULL) { q=P一>next ;//********found******** __________; //释放P所指向的节点 p=q; }} int Stack::Pop() { Item*temp; int ret;//********found******** ___________; //使temp指向栈顶节点 ret=top一>item; top=top一>next; delete temp; return ret;}void Stack::Push(const int&val){ Item*temp=new Item(val);//********found********__________;//使新节点的next指针指向栈顶数据 top=temp;}int main(){ Stack s; for(int i=1;i<Size;i++) s.Push(i); cout<<”The element of stack are:”; for(i=1;i<Size;i++) cout<<s.Pop()<<’\t’; return 0 ;}
【正确答案】正确答案:(1)item(val) (2)delete[]p (3)temp=top (4)temp一>next=top
【答案解析】解析:(1)主要考查构造函数,对私有成员进行初始化,即item(val)。 (2)主要考查使用delete语句释放指针,一般格式为:delete[]+指针。 (3)指向栈顶节点的是top指针,要使temp指向栈顶节点,故使用语句temp=top;。 (4)指向栈顶节点的是top指针,要使新节点的next指针指向栈顶数据,故使用语句temp一>next=top;。