堆栈实现
本人用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;
}