栈 C++ 适用各种数据类型,,仿Java API
来源:互联网 发布:pvf物品导入数据库 编辑:程序博客网 时间:2024/06/05 03:11
#ifndef STACK_HH#define STACK_HH#include<iostream>#include<stdlib.h>using namespace std;template <typename type>struct StackNode{ type value; StackNode *next; StackNode *previous;};template <typename type>class Stack{private: int len; StackNode<type> *top; StackNode<type> *head; StackNode<type> *tail; bool isReverse;public: Stack(); ~Stack(); bool isEmpty(); bool push(type value); type pop(); type getTop(); bool reverse(); bool isReversed(); int getLength();};template <typename type>Stack<type>::Stack(){ top = NULL; len = -1; isReverse = false;}template <typename type>bool Stack<type>::isEmpty(){ if(this->len == -1 || this->top == NULL) { return true; } return false;}template <typename type>bool Stack<type>::push(type value){ StackNode<type> *vNode = new StackNode<type>(); vNode->value = value; if(vNode == NULL) { return false; } if(len == -1 || this->top == NULL) { top = vNode; top->next = NULL; top->previous = NULL; this->head = vNode; this->tail = vNode; this->len++; return true; } //if the stack was reversed if(this->isReverse) { vNode->previous = this->tail; this->tail->next = vNode; this->tail = vNode; this->top = this->tail; } else { vNode->next = this->head; this->head ->previous = vNode; this->head = vNode; this->top = this->head; } this->len++; return true;}template <typename type>type Stack<type>::pop(){ if(len == -1 || this->top == NULL) { return NULL; } type temp = this->top->value; StackNode<type> *nTemp; if(this->isReverse) { nTemp = this->top; this->tail = this->top->previous; this->top = this->tail; free(nTemp); nTemp = NULL; } else { nTemp = this->top; this->head = this->top->next; this->top = this->head; free(nTemp); nTemp = NULL; } this->len--; return temp;}template <typename type>type Stack<type>::getTop(){if(len == -1 || this->top == NULL){return NULL;}return this->top->value;}template <typename type>bool Stack<type>::reverse(){ try{ if(this->len == -1) { return false; } if(this->isReverse) { this->top = this->head; this->isReverse = false; } else { this->top = this->tail; this->isReverse = true; } return true; }catch(...){ return false; }}template <typename type>bool Stack<type>::isReversed(){ return this->isReverse;}template <typename type>int Stack<type>::getLength(){ return this->len+1;}template <typename type>Stack<type>::~Stack(){ while(this->pop()) {}}#endif