一 代码结构
二 代码详解
1. doublestack.h
/*************************************************************************
> File Name: doublestack.h
> Author: wangzhicheng
> Mail: 2363702560@qq.com
> Created Time: Mon 16 Feb 2015 10:35:07 AM WST
************************************************************************/
#ifndef DOUBLESTACK_H
#define DOUBLESTACK_H
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <memory>
using namespace std;
template<class T>
class Double_stack {
private:
int top0;
int top1;
const int n;
T *array;
public:
Double_stack();
bool empty() const;
bool full() const;
bool push(const T&);
bool pop(T &);
~Double_stack();
};
#endif
2. doublestack.cpp
/*************************************************************************
> File Name: doublestack.cpp
> Author: wangzhicheng
> Mail: 2363702560@qq.com
> Created Time: Mon 16 Feb 2015 09:53:20 PM WST
************************************************************************/
#include "doublestack.h"
template<class T>
Double_stack<T>::Double_stack():n(1024) {
this->top0 = -1;
this->top1 = n;
this->array = new T(n);
if(!this->array) {
cerr << "memory lack...!" << endl;
exit(EXIT_FAILURE);
}
}
template<class T>
bool Double_stack<T>::empty() const {
return this->top0 == -1 && this->top1 == n;
}
template<class T>
bool Double_stack<T>::full() const {
return this->top0 + 1 == this->top1;
}
template<class T>
bool Double_stack<T>::push(const T& m) {
if(this->full()) {
cerr << "the stack is full...!" << endl;
exit(EXIT_FAILURE);
}
static int choice;
if(!choice) {
this->top0++;
this->array[top0] = m;
}
else {
this->top1--;
this->array[top1] = m;
}
choice = (choice + 1) & 1;
}
template<class T>
bool Double_stack<T>::pop(T& m) {
if(this->empty()) {
cerr << "the stack is empty...!" << endl;
exit(EXIT_FAILURE);
}
static int choice;
if(!choice) {
m = this->array[top0];
this->top0--;
}
else {
m = this->array[top1];
this->top1++;
}
choice = (choice + 1) & 1;
}
template<class T>
Double_stack<T>::~Double_stack() {
delete this->array;
this->top0 = -1;
this->top1 = n;
}
3. main.cpp
/*************************************************************************
> File Name: main.cpp
> Author: wangzhicheng
> Mail: 2363702560@qq.com
> Created Time: Mon 16 Feb 2015 10:20:01 PM WST
************************************************************************/
#include "doublestack.cpp"
int main() {
Double_stack<int>doublestack;
doublestack.push(1);
doublestack.push(2);
doublestack.push(3);
int m;
doublestack.pop(m);
cout << m << endl;
return 0;
}
4. makefile
CC=g++
all:
$(CC) -g -o main main.cpp doublestack.cpp doublestack.h
三 程序运行截图