PS:这题的关键是要了解“栈”这种数据结构的存储形式,要知道top指向的不是栈顶的元素,而是栈顶元素的下一位!
所以才有:栈空是top==0,栈满是top==MAX。
stack.h
// stack.h -- class definition for the stack ADT
#ifndef STACK_H_
#define STACK_H_
struct Customer
{
char fullname[35];
double payment;
};
typedef Customer Item;
class Stack
{
private:
enum {MAX = 10}; // constant specific to class
Item customers[MAX]; // holds stack items
double sum; //store the summation of payment
int top; // index for top stack item
public:
Stack();
bool isempty() const;
bool isfull() const;
// push() returns false if stack already is full, true otherwise
bool push(const Item & customer); // add item to stack
// pop() returns false if stack already is empty, true otherwise
bool pop(Item & customer); // pop top into item
double returnSum() const;
};
#endif
stack.cpp
// stack.cpp -- Stack member functions
#include "stack.h"
Stack::Stack() // create an empty stack
{
top = 0;
sum=0.0;
}
bool Stack::isempty() const
{
return top == 0;
}
bool Stack::isfull() const
{
return top == MAX;
}
bool Stack::push(const Item & customer)
{
if (top < MAX)
{
customers[top++] = customer;
return true;
}
else
return false;
}
bool Stack::pop(Item & customer)
{
if (top > 0)
{
sum += customers[--top].payment;
//注意不是sum+=customers[top].payment,因为top标记的其实是栈顶元素的下一位
customer = customers[top];
return true;
}
else
return false;
}
double Stack::returnSum() const
{
return sum;
}
main.cpp
// stacker.cpp -- testing the Stack class
#include <iostream>
#include <cctype> // or ctype.h
#include "stack.h"
int main()
{
using namespace std;
Stack st; // create an empty stack
char ch;
Customer cu;
cout << "Please enter A to add a customer,\n"
<< "P to process a customer, 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 customer's name: ";
cin.getline(cu.fullname,35);
cout << "Enter payment: ";
cin>>cu.payment;
if (st.isfull())
cout << "stack already full\n";
else
st.push(cu);
break;
case 'P':
case 'p':
if (st.isempty())
cout << "stack already empty\n";
else
{
st.pop(cu);
cout << cu.fullname << " payed.\n";
cout << "Now the summation of payment is " << st.returnSum() << " yuan.\n";
}
break;
}
cout << "\nPlease enter A to add a customer,\n"
<< "P to process a customer, or Q to quit.\n";
}
cout << "\nBye\n";
return 0;
}