c++ - 如何通过链表将最大大小为 20 添加到堆栈

标签 c++ linked-list stack

我已经通过链表实现了一个堆栈,如下所示,但我无法获得最大尺寸。我希望堆栈最多容纳 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/

相关文章:

c# - 文本差异应用程序如何工作?

c++ - 如何判断Windows是否安装了C/C++编译器?

java - 搜索并从链表中删除节点

c++ - 如何拥有按值 vector 并结合使用指针 vector ?

c++ - 模板类的重载赋值运算符

java - Qt Java - 从图库中获取图像

c++ - 链表 - 使用后指针在末尾插入

c - C 中链表的逆向算法

linux - 如何在 ucontext* ,linux 中释放堆栈?

c - 缓冲区溢出 - 局部变量在堆栈上的顺序