栈是限定仅在表头进行插入和删除操作的线性表。有着先进后出的特点(FILO);
如今我来动手实现栈的基本本功能练练手;
定义栈的头文件例如以下:
#ifndef CSTOCK_H_ #define CSTOCK_H_ const int STOCK_SIZE = 100;//定义栈的大小 typedef int elemType;//定义栈元素类型。眼下仅用int来练手 class CStock { public: CStock(); //构造函数,构造空栈; bool push(elemType x); //进栈操作; bool pop(elemType &x); //出栈操作; void clear(); //清空栈; bool isEmpty(); //推断是否栈空。 bool isFull(); //推断是否栈满。 void print(); //打印栈内元素; ~CStock(); private: elemType elem[STOCK_SIZE]; int top;//指向栈顶; }; #endif
实现基本功能例如以下:
#include "Stock.h" #include<iostream> using std::cout; using std::endl; //构造函数 CStock::CStock():top(-1) { } //进栈操作,进栈成功返回true,否则返回false; bool CStock::push(elemType x) { if(top == STOCK_SIZE - 1) { return false; } elem[++top] = x; return true; } //出栈操作,由形參x将元素带出主调函数。出栈成功返回true,否则返回false; bool CStock::pop(elemType &x) { if(top == -1) { return false; } x = elem[top--]; return true; } //清空栈,使栈为空。 void CStock::clear() { top = -1; } //推断栈是否为空 bool CStock::isEmpty() { return top == -1; } //推断栈是否栈满 bool CStock::isFull() { return top == STOCK_SIZE - 1; } //打印栈 void CStock::print() { for(int i = 0; i <= top; i++) { cout << elem[i] << "\t"; if( (i+1) % 5 == 0) cout << endl; } } //析构函数 CStock::~CStock(void) { }
原文链接: https://www.cnblogs.com/claireyuancy/p/6889286.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/254259
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!