Stack的实现和课后练习

#include "stdio.h"
#include "string.h"
enum Error_code{success,overflow,underflow,fail};

const int maxn=100;
typedef int Stack_entry;

class Stack
{
private:
    int top;
    Stack_entry entry[maxn];
public :
    Stack(){top=-1;memset(entry,0,sizeof(entry));}//用于初始化栈结构
    Error_code push(const Stack_entry&item);//元素入栈
    Error_code Top(Stack_entry&item);//返回栈顶元素,元素保留栈中
    int size();
    Error_code pop();//元素出栈,但出栈元素不被保留
    bool operator==(Stack &s);
};
//Stack.cpp

Error_code Stack::push(const Stack_entry&item)
{
    Error_code outcome=success;
    if(top>=maxn)
        outcome=overflow;
    else
        entry[++top]=item;
    return outcome;//元素入栈操作
}
Error_code Stack::pop()
{
    Error_code outcome=success;
    if(top==-1)
        outcome=underflow;
    else
        top--;
    return outcome;
}
Error_code Stack::Top(Stack_entry&item)
{
    Error_code outcome=success;
    if(top==-1)
        outcome=underflow;
    else
        item=entry[top];//top始终指向栈顶元素
    return outcome;
}
int Stack::size()
{
    return top+1;
}
bool Stack::operator==(Stack&s)//重载==运算符判断对象是否相等
{
    int item;
    int i;
    int count=top;
    if(s.size()!=top+1)
        return false;
    else
    {
        while(s.Top(item)!=underflow)
        {
            if(item!=entry[count--])
            return false;
            s.pop();
        }
    }
    return true;
}
//以上是Stack类的基本实现,当然这只是Stack类的一小部分

//作业:
Error_code copy(Stack&dest,Stack&source)
{
    Error_code outcome=success;
    Stack temp;//临时栈
    Stack_entry item;
    while(underflow!=source.Top(item))
    {
        temp.push(item);
        source.pop();
    }

    while(underflow!=temp.Top(item))
    {
        dest.push(item);
        source.push(item);
        temp.pop();
    }

    if(dest==source)
        return success;
    else
        return fail;
}//将栈source中的数据,复制到dest栈中,source栈没被改变
//主函数的实现
int main()
{
    Stack s;
    Stack d;
    int item;
    int i=0;
    printf("请输入 10 个元素:\nsource=");
    for(i;i<10;i++)
    {
        scanf("%d",&item);
        s.push(item);
    }
    printf("\n");
    for(i=0;i<10;i++)
    {
        s.Top(item);
        printf("dest= %d\n",item);
        s.pop();
    }
    if(success==copy(d,s))
       printf("复制成功!\n\n");
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值