一个简单的栈的实现

来源:互联网 发布:算法描述怎么写 编辑:程序博客网 时间:2024/04/30 08:24

下面的代码是一个简单的栈的实现。

1。该数据结构中的元素很简单,一个数组,一个指向栈顶的top

2。 初始化时,top为-1,且top为-1时也表示了该栈为空栈。

3。 因为top指向栈顶,压栈时,先top加1,在保存元素到栈顶

4。 因为top指向栈顶,弹栈时,先取出栈顶元素,再top减1。

5。 问题是pop时,如果是空栈,弹啥呢?

 

// =====================================================================================
//
//       Filename:  Stack.cpp
//
//    Description: 
//
//        Version:  1.0
//        Created:  09/06/2010 09:47:52 PM
//       Revision:  none
//       Compiler:  g++
//
//         Author:  YOUR NAME (),
//        Company: 
//
// =====================================================================================

#include    <iostream>
using namespace std;

#define MAX_STACK_SIZE 1024

template <class C> class Stack
{
    C stack[MAX_STACK_SIZE];
    int top;
public:
    Stack():top(-1){};
    ~Stack(){ cout << "release Stack" << endl;}
    int push(C item)
    {
        if (top >= (MAX_STACK_SIZE -1))
        {
            cout << "stack overflow" << endl;
            return -1;
        }
        cout << top << endl;
        stack[++top] = item;
    }
    C pop()
    {
        if (top == -1)
        {
            cout << "empty stack" << endl;
            return C(0);
        }
        return stack[top--];
    }
};

int
main ( int argc, char *argv[] )
{
    int i;
    Stack<char> string;
    string.push('a');
    string.push('b');
    string.push('c');
    string.push('d');
    for (i=0;i<5;i++)
        cout << string.pop() << endl;

    return 0;
}                // ----------  end of function main  ----------

原创粉丝点击