1. 程式人生 > 其它 >[C++][資料結構] 簡單靜態棧

[C++][資料結構] 簡單靜態棧

技術標籤:C++資料結構資料結構

要求:

  • 實現大小為10,資料型別為整型的靜態棧
  • 實現過程結合單例模式

思路:

  • 遊標_pstr始終指向下一個要被填充的空間
  • 資料入棧,遊標_pstr加1
  • 資料出棧,遊標_pstr減1

示例圖:

程式碼:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <iostream>

using std::cout;
using std::endl;

class Stack
{
public:
    static Stack *
getInstance() //單例模式實現相關 { if(nullptr==_pInstance) { _pInstance=new Stack(); } return _pInstance; } static void destroy() //單例模式實現相關 { if(_pInstance) { delete _pInstance; } } void print() { for
(int i=9;i>=0;i--) { cout << "data[" << i << "]= "<<_data[i] << endl; } } /***元素入棧***/ void push(int data); /***元素出棧***/ void pop(); /***讀出棧頂元素***/ int top(); /***判斷棧空***/ bool empty(); /***判斷棧滿***/
bool full(); private: Stack() : _pstr(0) { bzero(_data,sizeof(_data)); cout << "Stack()" << endl; } ~Stack() { cout << "~Stack()" << endl; } private: int _data[10]; int _pstr; static Stack *_pInstance; }; /***Stack類元素入棧實現***/ void Stack::push(int data) { if(_pstr<10) { _data[_pstr]=data; _pstr++; }else { cout << "error: Stack is full" << endl; } } /***Stack類元素出棧實現***/ void Stack::pop() { if(_pstr>0) { _pstr--; _data[_pstr]=0; }else { cout << "error: Stack is empty" << endl; } } /***Stack類讀棧頂元素實現***/ int Stack::top() { if(_pstr>0) { return _data[_pstr-1]; } return -1; } /***Stack類判斷棧空***/ bool Stack::empty() { if(0==_pstr) { return true; }else { return false; } } /***Stack類判斷棧滿***/ bool Stack::full() { if(10==_pstr) { return true; }else { return false; } } Stack * Stack::_pInstance=nullptr; int main() //測試 { Stack *s1=Stack::getInstance(); s1->push(10); s1->push(12); s1->push(14); cout << "top is " << s1->top() << endl; s1->pop(); cout << "top is " << s1->top() << endl; s1->pop(); cout << "top is " << s1->top() << endl; s1->pop(); cout << "top is " << s1->top() << endl; s1->pop(); for(int i=0;i<11;i++) { s1->push(i); } cout << "top is " << s1->top() << endl; Stack::destroy(); return 0; }

2021/1/18