一步一步建立一个栈

本文介绍了一个简单的栈类定义及其基本操作的实现,包括创建、入栈和出栈等核心功能,并通过一个主函数进行了测试。

December 9, 2015 1:20 PM

第一步:定义一个栈类
class node
{
    public:
        int data;               //存放数据
        class node *next;       //存放指针,指向下一个节点
};

class stack
{
    public:
        node *top;                      //栈顶
        node *bottom;                   //栈底
};
第二步:创建一个栈
stack *create()                         //创建栈
{
    stack *sta = new(stack);            //初始化栈,头尾指针均指向空
    sta->bottom = NULL;
    sta->top = NULL;

    return(sta);
}
第三步:入栈
stack *push(stack *sta, int x)
{
    node *newItem;
    newItem = new(node);
    newItem->data = x;
    newItem->next = NULL;

    if(sta->top == NULL)                    //如果队列为空
    {
        sta->bottom = newItem;
        sta->top = newItem;
    }
    else
    {
        sta->top->next = newItem;
        sta->top = newItem;
    }
    return(sta);
}
第四步:出栈
stack *pop(stack* sta)                      //出栈
{
    node *deleteItem;
    if(sta->top == NULL)                    //判断栈是否为空
    {
        cout << "these is nothing to delete!!!" << endl;
    }
    else
    {
        if(sta->bottom == sta->top)         //判断队列是否只有一个元素
        {
            deleteItem = sta->top;
            cout << "the deleted data is : " << deleteItem->data << endl;
            sta->bottom = NULL;
            sta->top = NULL;
        }
        else
        {
            deleteItem = sta->bottom;
            while(deleteItem->next != sta->top)
            {
                deleteItem = deleteItem->next;
            }
            sta->top = deleteItem;
            deleteItem = deleteItem->next;
            cout << "the deleted data is : " << deleteItem->data << endl;
        }
        delete(deleteItem);
        deleteItem = NULL;
    }
    return(sta);
}
第五步:主函数运行测试
int main(int argc, char** argv) {

    stack *sta = create();
    sta =  push(sta, 123);
    sta =  push(sta, 456);
    sta =  pop(sta);
    sta =  pop(sta);

    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值