【问题标题】:How to add max size of 20 to stack by linked list如何通过链表将最大大小为 20 添加到堆栈中
【发布时间】: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


【解决方案1】:

你本质上是想把东西包装在一个有大小变量的类中。

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 作为构建块,而不是结构本身。

【讨论】:

    【解决方案2】:

    所以我会使用某种结构,它带有指向头节点的指针和一个值来捕获堆栈的最大大小。当您压入堆栈时,您需要增加该值并检查以确保在压入之前它没有超过最大堆栈大小。此外,peek 通常是 showTop() 接受的函数名称。

    【讨论】:

      猜你喜欢
      • 2011-11-24
      • 2019-12-29
      • 2021-11-28
      • 2020-08-05
      • 2020-01-05
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多