分享

C++实现栈

 海漩涡 2014-09-04
///2014-09-04
///author txh
#include <iostream>

using namespace std;

template <class T>
struct Node
{
    Node<T> *next;
T data;
};

template <class T>
class stack
{
public:
stack()
{
        head = new Node<T>;
        if(NULL == head)
        {
            cout<<"new head error"<<endl;
}
else
{
            head->next = NULL;
head->data = NULL;
}
}
~stack()
{
        delete head;
}

    void push(T elem)
    {
        Node<T> *p = new Node<T>;
if(NULL == p)
{
            cout<<"new Node error"<<endl;
}
else
{
            p->data = elem;
p->next = head->next;
head->next = p;
}
}

T pop()
{
   T elem;
        Node<T> *p = head->next;

if(p!=NULL)
{
elem = p->data;
head->next = p->next;

delete p;
p = NULL;
}
else
{
            cout<<"This stack is NULL"<<endl;
return NULL;
}
return elem;
}

T top()
{
        T elem;
Node<T> *p = head->next;
if(p != NULL)
{
            elem = p->data;
return elem;
}
else
{
            cout<<"This stack is NULL"<<endl;
return NULL;
}
}

int stackSize()
{
        int size = 0;
Node<T> *p = head->next;

while(p != NULL)
{
            p = p->next;
size++;
}
return size;
}

bool judgeEmpty()
{
        Node<T> *p = head;
if(p->next == NULL)
{
            return true;
}
else
{
            return false;
}
}
private:
Node<T> *head;
};

int main(int argc,char *argv[])
{

    int i=0;
    stack<int> S;
S.push(100);
S.push(200);
S.push(300);
cout<<"the top:"<<S.top()<<endl;
cout<<"the size:"<<S.stackSize()<<endl;
if(S.judgeEmpty())
{
        cout<<"this empty"<<endl;
}
else
{
         cout<<"this isn't empty"<<endl;
}

for(i=0; i<3; i++)
{
   S.pop();
        cout<<"the top:"<<S.top()<<endl;
   cout<<"the size:"<<S.stackSize()<<endl;
}

return 0;
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约