C++ 类 实现栈
2015-11-27 10:31
465 查看
这个是类的实现“`
`
mian函数调用:
结果:
#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(); }
结果:
相关文章推荐
- C++贪吃蛇——(1)
- C++容器的拷贝注意细节
- C语言string家族函数使用说明及范例
- #if defined和#if !defined(c语言的宏定义)
- c++对ip和端口的处理
- 33.c/c++程序员面试宝典-函数重载
- 转: windows下C++ UI库 UI神器-SOUI
- C++中delete和delete[]的区别
- 汇编语言中的常数
- 二叉树遍历之递归实现(C++版)
- c语言编写一段小程序,出现了复制某个文件到一个找不到的路径里边
- 第10周项目3 利用二叉树遍历思想解决问题
- 第10周项目2 二叉树遍历的递归算法
- C语言结构体(struct)常见使用方法
- 千锋2015.04月最新C语言基础视频教程
- 为什么C++中只有指针和引用才能实现多态?
- oc语言学习之基础知识点介绍(四):方法的重写、多态以及self、super的介绍
- 一起talk C栗子吧(第六十四回:C语言实例--DIY字符串复制函数)
- C++得到成员变量的偏移值
- 《深入探索C++对象模型》笔记之第一章关于对象