我的问题是如何在不使用std::stack库的情况下实现Stack::top()函数?换句话说,我如何编写自己的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()相同,只是不会删除top元素。

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

10-11 22:53
查看更多