gpt4 book ai didi

c++ - 如何实现 stack::top() 函数?

转载 作者:行者123 更新时间:2023-11-30 04:09:22 25 4
gpt4 key购买 nike

我的问题是如何在不使用 std::stack 库的情况下实现 Stack::top() 函数?换句话说,我如何编写自己的 top() 函数来返回堆栈的顶部元素而不为后续堆栈弹出它?

谢谢。

#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;
}
}

最佳答案

因为你已经存储了top,你可以只返回p[top]。或者换句话说:top() 本质上与 pop() 相同,只是不会删除顶部元素。

关于c++ - 如何实现 stack::top() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21245455/

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