C++ 类 实现栈

这个是类的实现“`

#include<iostream>

using namespace std;
typedef int Item;

typedef struct node{
        Item data;
        struct node *pNext;
} Node, *pNode;
class STACK{
public: 
        int size;
        pNode Top;
        pNode Buttom;
public: STACK(pNode node,Item data);    
public: bool Push(pNode node,Item data);
        bool Pop();
        bool visit();
        bool IsEmpty();
        int Stack_size();       
        Item GetTOpData();
        bool ClearStack();
        bool DestroyStack();
};

`

#include"Stack.h"

// 构造函数,添加栈内元素
STACK::STACK(pNode node,Item data)
{
    node = new Node;
    if (node == 0)
    {
        cout << "new 失败" << endl;
        return;
    }
    this->Top = node;
    this->Buttom = node;
    this->size = 1;
    node->pNext = NULL;
    node->data = data;  
    return;

}

// 进栈
bool STACK::Push(pNode node, Item data)
{
    node = new Node;
    if (node == 0)
    {
        cout << "new 失败" << endl;
        return false;
    }
    node->pNext = this->Top;
    node->data = data;
    this->size++;
    this->Top = node;
    return true;
}

// 出栈
bool STACK::Pop()
{
    if (!this->size)
    {
        cout << "栈到底了" << endl;
        this->Top = NULL;
        return false;
    }
    pNode node;
    Item data;
    data = this->Top->data;
    node = this->Top;
    this->size--;
    this->Top = this->Top->pNext;
    delete node;  
    return true;
}
// 遍历站内的所有元素
bool STACK::visit()
{
    int size = this->size;
    if (size == 0)
        cout << "这是个空栈" << endl;
    pNode node = this->Top;
    while (size--)
    {
        cout << node->data << endl;
        node = node->pNext;
    }
    return true;
}

// 返回栈的大小
int STACK:: Stack_size()
{
    return this->size;
}

//为空返回true
bool STACK::IsEmpty()
{
    if (this->size ==0)
        return true;
    else
        return false;
}
// 获得栈顶元素
Item STACK::GetTOpData()
{
    return this->Top->data;
}

// 清除栈
bool STACK::ClearStack()
{
    while (this->IsEmpty() == false)
    {
        this->Pop();        
    }
    return true;
}

bool STACK::DestroyStack()
{
    pNode node = NULL;
    if (this->IsEmpty() == false)
    {
        node = this->Top;
        this->Top = this->Top->pNext;
        delete node;
    }
    cout << "已经摧毁栈"<<endl;
    return true;
}

mian函数调用:

#include "Stack.h"


int main()
{   
    int i =0;
    pNode pstack =NULL;
    STACK* stack = new STACK(pstack, 0);
    while (i < 20)
    {
        stack->Push(pstack, i+1);
        i++;
    }
    stack->visit();

    stack->ClearStack();

    stack->visit();

    stack->DestroyStack();
    stack->visit();
    getchar();
}

结果:这里写图片描述

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值