又一次造轮子-C++栈(泛型编程)

来源:互联网 发布:梦幻西游 for mac 编辑:程序博客网 时间:2024/05/29 14:23

栈,一种简单的数据结构,再造一次轮子

<<Stack.h>>

#if ! defined STACK_H_#define STACK_H_template<class Type>class Stack{private:    struct LinkStack    {        Type ele;        LinkStack *next,*previous;    };    LinkStack *linkstack,*newnode;    int size;public:    Stack();    ~Stack();    Type Top();    void Push(Type e);    void Pop(); //为空时特殊处理    int Size();    bool isEmpty();};#endif

<<Stack.cpp>>

#include<cstdlib>#include "Stack.h"template<class Type>int Stack<Type>::Size(){    return size;}template<class Type>bool Stack<Type>::isEmpty(){    return !size;}template<class Type>Stack<Type>::Stack(){    size = 0;}template<class Type>Type Stack<Type>::Top(){    return linkstack->ele;}template<class Type>void Stack<Type>::Push(Type e){    newnode = new LinkStack;    newnode->ele = e;    if(size)    {        newnode->previous = linkstack;    }    linkstack = newnode;    ++size;}template<class Type>void Stack<Type>::Pop(){    if(size && size != 1)    {        newnode = linkstack;        linkstack = linkstack->previous;        delete[] newnode;    }    else if(size==1)    {        delete[] linkstack;    }    --size;}template<class Type>Stack<Type>::~Stack(){    while(size)    {        Pop();    }}
<<TestStack.cpp>

#include "Stack.cpp"#include<iostream>using namespace std;struct A{    int x,y;};class B{public:    int x,y;};int C;int main(){    Stack<A> sta1;    Stack<B> sta2;    Stack<int> sta3;    A a;    for(int i=0;i<10;i++)    {        a.x = a.y = i;        sta1.Push(a);    }    cout<<"A:"<<endl;    cout<<sta1.isEmpty()<<endl;    cout<<sta1.Size()<<endl;    cout<<"Test A"<<endl;    for(int i=0;i<10;i++)    {        A temp = sta1.Top();        cout<<"x:"<<temp.x<<" y:"<<temp.y<<endl;        sta1.Pop();    }    cout<<"A:"<<endl;    cout<<sta1.isEmpty()<<endl;    cout<<sta1.Size()<<endl;    B b;    for(int i=0;i<10;i++)    {        b.x = b.y = i;        sta2.Push(b);    }    cout<<"B:"<<endl;    cout<<sta2.isEmpty()<<endl;    cout<<sta2.Size()<<endl;    cout<<"Test B"<<endl;    for(int i=0;i<10;i++)    {        B temp = sta2.Top();        cout<<"x:"<<temp.x<<" y:"<<temp.y<<endl;        sta2.Pop();    }    cout<<"B:"<<endl;    cout<<sta2.isEmpty()<<endl;    cout<<sta2.Size()<<endl;    cout<<"Test C"<<endl;    for(int i=0;i<10;i++)    {        sta3.Push(i);    }    cout<<"C:"<<endl;    cout<<sta3.isEmpty()<<endl;    cout<<sta3.Size()<<endl;    for(int i=0;i<10;i++)    {        cout<<sta3.Top()<<endl;        sta3.Pop();    }    cout<<"C:"<<endl;    cout<<sta3.isEmpty()<<endl;    cout<<sta3.Size()<<endl;}



1 0
原创粉丝点击