第十二章编程练习(4)

来源:互联网 发布:wkwebview js oc 编辑:程序博客网 时间:2024/05/13 01:04

STACK.h

#pragma once#ifndef STACK_H_#define STACK_H_typedef unsigned long Item;class Stack {private:enum { MAX = 10 };Item * pitems;int size;//需要创建的数组大小int top;//数组下标public:Stack(int n = MAX);Stack(const Stack & st);~Stack();bool isfull()const;bool isempty()const;bool push(const Item & item);bool pop(Item & item);Stack & operator=(const Stack & st);};#endif

STACK.cpp

#include "STACK.h"#include <iostream>Stack::Stack(int n){pitems = new Item[n];pitems[0] = 0;size = n;top = 0;}Stack::Stack(const Stack & st){size = st.size;pitems = new Item[size];for (int i = 0; i < size; i++)*(pitems+i) = *(st.pitems+i);top = st.top;}Stack::~Stack(){delete[]pitems;}bool Stack::isfull() const{return top==size;}bool Stack::isempty() const{return top==0;}bool Stack::push(const Item & item){if (top < size){*(pitems + (top++)) = item;return true;}elsereturn false;}bool Stack::pop(Item & item){if (top > 0){item = *(pitems + (--top));return true;}elsereturn false;}Stack & Stack::operator=(const Stack & st){size = st.size;for (int i = 0; i < size; i++)*(pitems + i) = *(st.pitems + i);top = st.top;return *this;}


main.cpp

#include <iostream>#include "STACK.h"#include <cstdlib>#include <cctype>using namespace std;int main(){Stack st;char ch;unsigned long po;cout << "Please enter A to add a purchase order,\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 PO number to add: ";cin >> po;if (st.isfull())cout << "stack already full\n";elsest.push(po);break;case'P':case'p':if (st.isempty())cout << "stack already empty\n";else {st.pop(po);cout << "PO #" << po << " popped\n";}break;}cout << "Please enter A to add a purchase order,\n"<< "P to process a PO, or Q to quit.\n";}Stack st1;st1 = st;cout << "process a PO:\n";st1.pop(po);cout << "PO #" << po << " popped\n";Stack st2(st);cout << "PO #" << po << " popped\n";system("pause");return 0;}


0 0