顺序栈

论坛 期权论坛 脚本     
匿名网站用户   2020-12-21 09:07   73   0

1、C++版的顺序栈

/***********************/
/*****  seqStack.h  ****/
/***********************/

#ifndef _SEQSTACK_H
#define _SEQSTACK_H

template <class T>
class SeqStack
{
    public:
        SeqStack(int capacity = 15);
        ~SeqStack();

        void ChangeCapacity(T* &st, int oldCapacity, int newCapacity);
        bool IsEmpty() const;
        T& Top() const;
        void Push(const T& item);
        T Pop();

    private:
        T *stack;
        int capacity;
        int top;
};

template <class T>
SeqStack<T>::SeqStack(int stackCapacity):capacity(stackCapacity)
{
    if (capacity < 1)
        throw "Stack capacity must be > 0";
    stack = new T[capacity];
    top = -1;
}

template <class T>
SeqStack<T>::~SeqStack()
{
    delete[] stack;
}

template <class T>
void SeqStack<T>::ChangeCapacity(T* &st, int oldCapacity, int newCapacity)
{
    if (newCapacity < 0)
        throw "Realloc storge cannot < 0";

    T *temp = new T[newCapacity];

    int number = std::min(oldCapacity, newCapacity);
    std::copy(st, st + number, temp);

    delete[] st;
    st = temp;
    capacity = newCapacity;
}

template <class T>
bool SeqStack<T>::IsEmpty() const
{
    return (top == -1);
}

template <class T>
inline T& SeqStack<T>::Top() const
{
    if (IsEmpty())
        throw "Stack is empty!";
    return stack[top];
}

template <class T>
void SeqStack<T>::Push(const T& item)
{
    if (top == capacity-1){
        ChangeCapacity(stack, capacity, 2*capacity);
    }

    stack[++top] = item;
}

template <class T>
T SeqStack<T>::Pop()
{
    if (IsEmpty())
        throw "Stack is empty!";
    return stack[top--];
}

#endif
/***********************/
/*****   main.cpp   ****/
/***********************/

#include <iostream>
#include "seqStack.h"

using namespace std;

int main(int argc, const char *argv[])
{
    SeqStack<int> st;

    int i;

    if (st.IsEmpty())
        cout << "Stack is empty!" << endl;

    cout << "Push data in..." << endl;
    for (i = 0; i < 30; i++){
        st.Push(i);
        cout << st.Top() << "  ";
    }
    cout << endl;

    cout << "Top of stack" << endl;
    cout << st.Top() << endl;

    cout << "Pop data out..." << endl;
    for (i = 0; i < 30; i++)
        cout << st.Pop() << "  ";
    cout << endl;

    return 0;
}
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP