用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,\n");
    printf("P to process a PO, or Q to quit.\n");
    while((1 == scanf("%c", &ch)) && ch != 'Q' && ch != 'q')
    {
        if(!isalpha(ch))
        {
            printf("\aOrder: P or Q !\n");
            continue;
        }
        switch(ch)
        {
            case 'A':
            case 'a':
                printf("Enter a PO number to add: ");
                scanf("%d", &po);
                if(st.isfull())
                    printf("Stack already full\n");
                else
                    st.push(po);
                break;
            case 'P':
            case 'p':
                if(st.isempty())
                    printf("stack already empty\n");
                else
                {
                    st.pop(po);
                    printf("PO #%d popped\n", po);
                }
                break;
        }
        // 清除空白字符,必须放到后面,因为swith中有输入,会留下回车符
        while(getchar() != '\n')
            continue;
        printf("Please enter A to add a purchase order,\n");
        printf("P to process a PD, or Q to quit.\n");
    }
    printf("Bye!\n");
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值