我如何实现stack :: top()函数?

时间:2014-01-20 22:26:35

标签: c++ stack

我的问题是如何在不使用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;
    }
}

1 个答案:

答案 0 :(得分:2)

由于您已经存储了top,因此您只需返回p[top]即可。换句话说:top()基本上与pop()相同,它只是不会删除顶部元素。