[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;
}


展开阅读全文
©️2020 CSDN 皮肤主题: 黑客帝国 设计师: 上身试试 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值