【发布时间】:2019-03-26 18:51:43
【问题描述】:
如下所示,我已经通过链表实现了一个堆栈,但我无法获得最大尺寸来工作。我希望堆栈最多容纳 20 个项目,并在堆栈已满时显示。
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *link;
};
Node *top = NULL;
bool isempty()
{
if(top == NULL)
return true; else
return false;
}
void push (int value)
{
Node *ptr = new Node();
ptr->data = value;
ptr->link = top;
top = ptr;
}
void pop ( )
{
if ( isempty() )
cout<<"Stack is Empty";
else
{
cout << "pop element" << endl;
Node *ptr = top;
top = top -> link;
delete(ptr);
}
}
void showTop()
{
if ( isempty() )
cout<<"Stack is Empty";
else
cout<<"Element at top is : "<< top->data << endl;
}
void displayStack()
{
//print stack
if ( isempty() )
cout<<"Stack is Empty" << endl;
else
{
cout << "Stack: " << endl;
Node *temp=top;
while(temp!=NULL)
{ cout<<temp->data<<" ";
temp=temp->link;
}
cout<<"\n";
}
}
我想要一个类似于我的 isEmpty() 但 isFull() 的函数,当堆栈中有 20 个项目时显示堆栈已满。我没有在上面的 sn-p 中包含我的 main 函数,因为我只是调用了我的函数。
感谢所有非常感谢的建议 :) 我对 c++ 相当了解,所以放轻松。
【问题讨论】:
-
如果你想要最多 20 个对象,为什么要使用链表?一个数组就足够了。链表的部分好处是没有最大值(当然,您的程序可以使用的总内存除外)。
-
你将如何计算物品的数量?不知何故,通过某种方式(可能创建一个类、重新排列代码等),您必须在某处放置一个计数器——也许弄清楚这是任务的一部分。至于代码——你展示的代码完全错过了如何跟踪这些信息。事实上,这主要是一个设计问题,而不是
pop()或displayStack()的详细信息。
标签: c++ linked-list stack