我已经通过链表实现了一个堆栈,如下所示,但我无法获得最大尺寸。我希望堆栈最多容纳 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 个项目时堆栈已满。我没有在上面的代码片段中包含我的主要功能,因为我只是调用我的功能。
非常感谢您提供的所有建议 :) 我对 C++ 相当了解,所以不要着急。
最佳答案
本质上,您希望将所有内容包装在一个具有大小变量的类中。
struct Stack
{
struct Node
{
int data;
Node * link;
};
Node * top = NULL;
size_t size = 0U;
void push(int val)
{
// stuff you already have
++size;
}
void pop()
{
// stuff you already have
--size;
}
// other methods you have
};
Node 不知道列表中有多少个,因此您需要将 Node 用作构建 block ,而不是结构本身。
关于c++ - 如何通过链表将最大大小为 20 添加到堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55364372/