您的位置:首页 > 编程语言 > C语言/C++

C++ 类 实现栈

2015-11-27 10:31 465 查看
这个是类的实现“`

#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();
}


结果:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: