Stack类实现。模板 4年前

编程语言
577
Stack类实现。模板
// Head.h
#include <iostream>
using namespace std;

#ifndef DEFAULT_STACK_SIZE
#define DEFAULT_STACK_SIZE 1000
#endif

// end 
// iCoding@CodeLab
//

// Stack.h
#include "Head.h"


template <typename ElemType>
class Stack
{
    private:
        ElemType *data;
        int size;
        int bottom;
        int top;
    public:
        Stack ();
        void push (ElemType elem);
        ElemType pop ();
        bool is_empty ();
        bool is_full ();
        int get_size ();
        void expand_size ();
};


// end 
// iCoding@CodeLab
//

#include "Stack.h"

///////////////////////////////////////////////////////////
// Stack
template <typename ElemType>
Stack<ElemType>::Stack ()
{
    this->size   = DEFAULT_STACK_SIZE;
    this->data   = new ElemType[this->size+1];
    this->bottom = 0;
    this->top    = 0;
}

///////////////////////////////////////////////////////////
// push 
template <typename ElemType>
void Stack<ElemType>::push (ElemType elem)
{
    if (is_full())
    {
        expand_size ();
    }
    this->top++;
    this->data[this->top] = elem;
}
///////////////////////////////////////////////////////////
// pop
template <typename ElemType>
ElemType Stack<ElemType>::pop ()
{
    ElemType elem_top;
    elem_top = this->data[this->top];
    this->top--;
    return elem_top;
}
///////////////////////////////////////////////////////////
// is empty
template <typename ElemType>
bool Stack<ElemType>::is_empty ()
{
    return (this->bottom >= this->top);
}

///////////////////////////////////////////////////////////
// is full
template <typename ElemType>
bool Stack<ElemType>::is_full ()
{
    return (this->size <= this->top);
}

///////////////////////////////////////////////////////////
// get size of Stack
template <typename ElemType>
int Stack<ElemType>::get_size ()
{
    return (this->top - this->bottom);
}

///////////////////////////////////////////////////////////
// expand_size
template <typename ElemType> 
void Stack<ElemType>::expand_size ()
{
    ElemType* elem_data_tmp;
    elem_data_tmp = new ElemType[this->size+1];
    for (int i = this->bottom + 1; i <= this->top; i++)
    {
        elem_data_tmp[i] = this->data[i];
    }
    delete[] this->data;
    this->size += DEFAULT_STACK_SIZE;
    this->data = new ElemType[this->size+1];
    for (int i = this->bottom + 1; i <= this->top; i++)
    {
        this->data[i] = elem_data_tmp[i];
    }
}

// end 
// iCoding@CodeLab
//
圈圈在叉叉
人若是失去了情感,泯灭了希望,那和一团只有逻辑的人工智能有什么区别?
3
发布数
3
关注者
2057
累计阅读

热门教程文档

Rust
84小节
爬虫
6小节
Lua
21小节
10.x
88小节
Java
12小节
广告