gpt4 book ai didi

c++ - 如何在 C++ 中实现可动态调整大小的堆栈?

转载 作者:行者123 更新时间:2023-11-28 00:35:15 25 4
gpt4 key购买 nike

我现在的代码只是一个具有推送、弹出和显示方法的简单堆栈。如何更改我的堆栈,以便堆栈的大小根据输入的元素数量动态调整大小?因此,例如,如果堆栈已满,我会创建一个两倍于原始堆栈大小的新堆栈,并将数据复制到新堆栈中。

谢谢。

#include <iostream>
#include <stdexcept>

using namespace std;

class Stack
{
private:
int *p;
int top,length;

public:
Stack(int = 0);
~Stack();

void push(int);
int pop();
void display();
};

Stack::Stack(int size)
{
top=-1;
length=size;
while(length <= 0) //If the stack size is zero, allow user to mention it at runtime
{
cout<<"Stack of zero size"<<endl;
cout<<"Enter a size for stack : ";
cin >> length;
}
p=new int[length];
}

Stack::~Stack()
{
delete [] p;
}

void Stack::push(int elem)
{
if(top==(length-1)) //If the top reaches to the maximum stack size
{
throw overflow_error("Can't push onto a full stack");
}
else
{
top++;
p[top]=elem;
}
}
int Stack::pop()
{
if(top==-1)
{
throw underflow_error("Can't pop from an empty stack");
}
int ret=p[top];
top--;
length--;

return ret;
}

void Stack::display()
{
for(int i = 0; i <= top; i++)
cout<<p[i]<<" ";
cout<<endl;
}

int main()
{
int len;

cout<<"Enter a size for stack : ";
cin >> len;
Stack s1(len);
try{
s1.push(1);
s1.display();
s1.push(2);
s1.push(3);
s1.push(4);
s1.push(5);
s1.display();
s1.pop();
s1.display();
s1.pop();
s1.display();
s1.pop();
s1.display();
s1.pop();
s1.display();
s1.pop();
s1.display();
}
catch(overflow_error){
cerr<< "Illegal operation. Cannot push onto a full stack.";
return -1;
}
catch(underflow_error){
cerr<< "Illegal operation. Cannot pop from an empty stack.";
return -1;
}


}

最佳答案

void Stack::push(int elem)
{
if(top==(length-1)) //If the top reaches to the maximum stack size
{
int* newp = new int[length * 2];
std::memcpy(newp, p, sizeof(int) * length);
delete[] p;
p = newp;
top++;
p[top]=elem;
length*=2;
}
else
{
top++;
p[top]=elem;
}

关于c++ - 如何在 C++ 中实现可动态调整大小的堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21177895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com