栈类

C++ code

#pragma once
#include "stdafx.h"

template<class T>
class CStack
{
public:
    CStack()
    {
        top=new SNode;
        top->prior=NULL;
        base=top;
        length=0;
    }
    bool isEmpty()
    {
        if(base==top)
            return 1;
        return 0;
    }
    void push(T data)//压栈、进栈
    {
        SNode* tmp=new SNode;
        tmp->data=data;
        tmp->prior=top;
        top=tmp;
    }
    T pop()//谈栈、出栈
    {
        if(!isEmpty())
        {
            T tmpData=top->data;
            SNode* tmp=new SNode;
            tmp=top;
            top=top->prior;
            delete tmp;
            return tmpData;
        }
    }
    T getTop()
    {
        if(!isEmpty()) return top->data;
    }
    void display()
    {
        SNode* tmp=new SNode;
        tmp =top;
        do{
            printf("%d,",tmp->data);
            tmp=tmp->prior;
        }while(tmp->prior);
        printf("\n");
    }

protected:
private:
    typedef struct SNode{
        T data;
        struct SNode* prior;//前一个元素的指针
    }SNode;
    SNode* top;
    SNode* base;
    int length;//栈的大小
};

 

posted @ 2017-09-28 15:14  TQCAI  阅读(173)  评论(0编辑  收藏  举报