c++のスタックスタック実装

2286 ワード

C++Stack(スタック)はコンテナクラスの改編であり、プログラマーにスタックのすべての機能を提供している.すなわち、先進的な後出(FILO)データ構造を実現している.
c++stlスタックstackのヘッダファイルは:
#include  
c++stlスタックstackのメンバー関数の紹介
オペレーション比較とスタックの割り当て
Empty()スタックが空の場合は真を返す
pop()スタックトップ要素の除去
push()スタックの上部に要素を追加
size()戻りスタック内の要素数
top()はスタックトップ要素を返します
stack.cpp
#include

template
class stackNode
{
 public:
    stackNode():next(NULL){}
    T data;// 
    stackNode* next;//          
};

template
class mystack
{
private:
    unsigned int stacklength;
    stackNode* node;//    
    stackNode* headnode;//   
    public:
        mystack();//   
        unsigned int length();//      
        void push(T x);//  
        bool isEmpty();//       
        void pop();//  
        T top();//      
        void clear();//   

};


template
mystack::mystack()
{
    node=NULL;
    headnode=NULL;
    stacklength=0;
}


template
inline unsigned int mystack::length(){return stacklength;}


template
void  mystack::push(T x)
{
    node=new stackNode();
    node->data=x;
    node->next=headnode;// node     
    headnode=node;
    ++stacklength;
}


template
bool  mystack::isEmpty()
{
    return stacklength==0;
}


template
void  mystack::pop()
{
    if(isEmpty()) return;
    node=headnode;
    headnode=headnode->next;//            
    delete(node);//     
    --stacklength;
}


template
T  mystack::top()
{
    if(!isEmpty())
    return headnode->data;
}


template
void  mystack::clear()
{
    while(headnode!=NULL)
    {
        node=headnode;
        headnode=headnode->next;
        delete(node);
    }
    node=NULL;
    headnode=NULL;
    stacklength=0;
}

using namespace std;

int main(int argc,char **argv)
{
	mystack  *p = new mystack;

	int a=10;
	p->push(a);
	p->push(a+1);
	p->push(a+2);
	p->push(a+3);
	p->push(a+4);

	for(int i=0;i<5;i++){
		cout << p->top() << "len=" << p->length() << endl;
		p->pop();
	}
	
	return 0;
}