| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 618 人关注过本帖
标题:堆栈实现
只看楼主 加入收藏
zzt_428
Rank: 2
来 自:南京师范大学
等 级:论坛游民
威 望:2
帖 子:243
专家分:22
注 册:2008-7-6
收藏
 问题点数:0 回复次数:0 
堆栈实现
本人用C++写了一个简单的实现堆栈的程序,是C++ primer plus 5th 后面的一个编程练习题,拿出来大家讨论讨论,看有什么地方可以改进的~~
//------stack.h
#ifndef STACK_H_
#define STACK_H_



struct Customer
{
    char fullname[35];
    double payment;
};
typedef Customer Item;

class Stack
{
public:
    Stack();
    bool isempty() const;
    bool isfull() const;
    bool push(const Item &item);
    bool pop(Item &item);
private:
    enum{MAX=5};
    Item items[MAX];
    int top;
    
};
#endif

//stack.cpp--类的实现
#include "stack.h"

Stack::Stack()
{
    top=0;
}

bool Stack::isempty() const
{
    return top == 0;
}

bool Stack::isfull() const
{
    return top == MAX;
}

bool Stack::push(const Item &item)
{
    if(top < MAX)
    {
        items[top++]=item;
        return true;
    }
    else
        return false;
}

bool Stack::pop(Item &item)
{
    if(top != 0)
    {
        item=items[--top];
        return true;
    }
    else
        return false;
}


//usestack.cpp ---使用堆栈

#include <iostream>
#include <cctype>
#include "stack.h"

static int tot=0;

int main()
{
    using namespace std;
    Stack st;
    char ch;
    Customer ct;
    cout << "PLease enter A to add a customer.\n"
         << "P to process a PO, or Q to quit.\n";
    while(cin >> ch && toupper(ch) != 'Q')
    {
        while(cin.get() != '\n')
            continue;
        if(!isalpha(ch))
        {
            cout << "\a";
            continue;
        }
        switch(ch)
        {
        case 'A':
        case 'a':cout << "Enter a Customer to add: \n";
                 cout << "Name:  ";
                 cin >> ct.fullname;
                 cout << "Payment: ";
                 cin >> ct.payment;
                 if(st.isfull())
                     cout << "The stack is already full.\n";
                 else
                     st.push(ct);
                 break;
        case 'P':
        case 'p':if(st.isempty())
                     cout << "Stack already empty.\n";
                  else
                  {
                      st.pop(ct);
                      tot += ct.payment;
                      cout << "Pop# :" << ct.fullname << endl;
                  }
                  break;
                  
        }
        cout << "Please enter A to add a purchase order.\n"
            << "P to process a PO, or Q to quit.\n";
    }
    cout << "The total payment$: " << tot << endl;
    cout << "Bye\n";

    return 0;
}
搜索更多相关主题的帖子: 堆栈 
2008-12-06 22:43
快速回复:堆栈实现
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015243 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved