[2013.9.27][cpp]一个简单的链接栈模型

学数据结构的一点想法

LinkStack.h文件:


#ifndef LINKSTACH_H
#define LINKSTACH_H

#include <stdexcept>
using std::exception;

template<class Entry>
class LinkStack
{
private:
        //template<class Entry>
        struct StackToken
        {
                Entry data;
                StackToken *next;
        };

        StackToken *ptr;
        size_t count;

        void freeptr()
        {
                StackToken *nptr = ptr;
                while(nptr)
                {
                        StackToken *tmp = nptr->next;
                        delete nptr;
                        nptr = tmp;
                }
        }

        void initptr(StackToken *p)
        {
                StackToken *nptr = p.
                        **tail = &ptr;
                while(nptr)
                {
                        StackToken *tmp = new StackToken;
                        tmp->data = nptr->data;
                        *tail = tmp;
                        nptr = nptr->next;
                        tail = &(*tail)->next;
                }
                *tail = 0;
        }

public:
        LinkStack() : ptr(0), count(0) {}

        ~LinkStack() {freeptr();}

        LinkStack(const LinkStack &that) {initptr(that->ptr);}

        LinkStack& operator=(const LinkStack &that)
        {
                if(this != *that)
                {
                        freeptr();
                        initptr(that->ptr);
                }
        }

        void push(const Entry &e)
        {
                StackToken *t = new StackToken;
                t->data = e;
                t->next = ptr;
                ptr = t;
                count++;
        }

        void pop()
        {
                if(!count) throw exception("栈已空!");
                StackToken *t = ptr;
                ptr = t->next;
                delete t;
                count--;
        }
         
        bool empty() {return count == 0;}

        Entry top()
        {
                if(!count) throw exception("栈已空!");
                return ptr->data;
        }

};

#endif //LINKSTACH_H


main.cpp文件:


#include "LinkStack.h"
#include <iostream>
using namespace std;

int main()
{

        LinkStack<int> psgs;
        int n;
        cout << "请输入游客人数:" << endl;
         cin >> n;
        cout << "按顺序输入乘客编号:" << endl;
        for(int i = 0; i < n; i++)
         {
                 int item;
                 cin >> item;
                psgs.push(item);
        }
        cout << "乘客下车次序是:" << endl;
        while(!psgs.empty())
        {
                cout << psgs.top() << ' ';
                psgs.pop();
        }
        cout << endl;
        system("pause");
        return 0;
}


posted @ 2014-05-16 21:31  绝不原创的飞龙  阅读(8)  评论(0编辑  收藏  举报  来源