C++クラスで簡単なスタックを実現


             ,      :

1.ヘッダファイルstack.h
// stack.h -- class definition for the stack ADT
#ifndef STACK_H_
#define STACK_H_

typedef unsigned long Item;

class Stack
{
private:
    enum {MAX = 10};
    Item items[MAX];
    int top;
public:
    Stack();
    bool isempty() const;
    bool isfull() const;
    // push() returns false if stack already is full, ture otherwise
    bool push(const Item & item);   // add item to stack
    // pop() returns false if stack already is empty, ture otherwise
    bool pop(Item & item);
};

#endif

2.クラス関数定義stack.cpp
// stack.cpp -- Stack member functions
#include "stack.h"

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

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

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

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

3.テスト、販売員の行動をシミュレートする——バスケットの一番上のものを先に処理する
// stacker.cpp -- testing the Stack class
#include <stdio.h> //    c        
#include <ctype.h> // or cctype for c++
#include <stdlib.h>
#include "stack.h"

int main()
{
    Stack st;
    char ch;
    unsigned long po;
    printf("Please enter A to add a purchase order,
"
); printf("P to process a PO, or Q to quit.
"
); while((1 == scanf("%c", &ch)) && ch != 'Q' && ch != 'q') { if(!isalpha(ch)) { printf("\aOrder: P or Q !
"
); continue; } switch(ch) { case 'A': case 'a': printf("Enter a PO number to add: "); scanf("%d", &po); if(st.isfull()) printf("Stack already full
"
); else st.push(po); break; case 'P': case 'p': if(st.isempty()) printf("stack already empty
"
); else { st.pop(po); printf("PO #%d popped
"
, po); } break; } // , , swith , while(getchar() != '
'
) continue; printf("Please enter A to add a purchase order,
"
); printf("P to process a PD, or Q to quit.
"
); } printf("Bye!
"
); system("pause"); return 0; }