请打开考生文件夹下的解决方案文件proj2,该工程中含有一个源程序文件proj2.cpp,请将堆栈类的定义补充完整。使程序的输出结果为:
The element of stack are:4 3 2 1
注意:请勿修改主函数main和其他函数中的任何内容,只在横线处编写适当代码,不要改动程序中的其他内容,也不要删除或移动“//****found****”。
t //proj2.cpp
2 #include<iostream>
3 using namespace std;
4 const int size=5 ;
5 class Stack;
6 class Item
7 {
8 public:
9 //********found********
10 Item(const int& val):___________ {}//构造函数对item进行初始化
11 private:
12 int item;
13 Item*next;
14 friend class Stack;
15 };
16 class Stack
17 {
18 public:
19 Stack():top(NULL){}
20 ~Stack();
21 int Pop();
22 void Push(const int &);
23i private:
24 Item*top;
25 };
26 Stack::~Stack()
27 {
28 Item*p=top,*q;
29 while(p!=NULL)
30 {
31 q=p一>next ;
32 //********found********
33 _____________; //释放p所指向的节点
34 p=q;
35 }
36 }
37 int Stack::Pop()
38 {
39 Item*temp ;
40 int ret;
41 //**********found**********
42 ___________; //使temp指向栈顶节点
43 ret=top->item;
44 top=top->next;
45 delete temp;
46 return ret;
47 }
48 void Stack::Push(const int&val)
49 {
50 Item*temp=new Item(val);
51 //**********found**********
52 }
//使新节点的next指针指向栈顶数据
53 top=temp;
54 )
55 int main()
56 {
57 Stack s;
58 for(int i=1;i<Size;i++)
59 s.Push(i);
60 cout<<"The element of stack are:";
61 for(i=1;i<Size;i++)
62 cout<<s.Pop()<<'\t';
63 return 0;
64 }
【正确答案】(1)itern(val)
(2)delete []p
(3)temp=top
(4)temp->next=top
【答案解析】(1)主要考查构造函数,对私有成员进行初始化,即item(val)。
(2)主要考查使用ctelete语句释放指针,一般格式为:delete[]+指针。
(3)指向栈顶节点的是top指针,要使temp指向栈顶节点,故使用语句temp=top;。
(4)指向栈顶节点的是top指针,要使新节点的next指针指向栈顶数据,故使用语句temp->next=top:。