一個數組實現兩個棧

一個數組實現兩個棧 --

方法1

定義一個數組,將數組首元素的前一個位置定義爲第一個棧的起始位置,每次入棧先將下標加一;
將數組最後一個元素的後一個位置定義爲第二個棧的起始地址,每次入棧都將下標減一;
侷限:數組的大小不能動態開闢,當數組用完之後,兩個棧都無法使用

#define MaxSize 100
class DoubleStack
{
public:
 DoubleStack()
  :_topIndex1(0)
  ,_topIndex2(1)
 {}
 void Push1(int x)
 {
  if (_topIndex1 < MaxSize)
  {
   _array[_topIndex1] = x;
   _topIndex1 += 2;
  }
  else
  {
   cout<<"Stack1 Is Full"<<endl;
  }
 }
 void Push2(int x)
 {
  if (_topIndex2 < MaxSize)
  {
   _array[_topIndex2] = x;
   _topIndex2 += 2;
  }
  else
  {
   cout<<"Stack2 Is Full"<<endl;
  }
 }
 void Pop1()
 {
  if (_topIndex1 > 0)
  {
   _topIndex1 -= 2;
  }
  else
  {
   cout<<"Stack1 Is Empty"<<endl;
  }
 }
 void Pop2()
 {
  if (_topIndex2 > 0)
  {
   _topIndex2 -= 2;
  }
  else
  {
   cout<<"Stack2 Is Empty"<<endl;
  }
 }
 int Top1()
 {
  return _array[_topIndex1 - 2];
 }
 int Top2()
 {
  return _array[_topIndex2 - 2];
 }
 bool IsStack1Empty()
 {
  return _topIndex1 > 0;
 }
 bool IsStack2Empty()
 {
  return _topIndex2 > 1;
 }
private:
 int _array[MaxSize];
 int _topIndex1;
 int _topIndex2;
};


方法2

將奇數位下標定義爲一個棧,將偶數位下標定義爲第二個棧;
入棧時將對應下標加二;
侷限:當兩個棧增長速度不一樣時,增長慢的會浪費很多空間

#include<iostream>
using namespace std;
#define maxsize 100
int Array[maxsize] = { 0 };
class Stack{
public:
 Stack(int topIndex, int* array = Array)        //構造函數
  :_array(Array)
  ,_topIndex(topIndex)
  , _beginIndex(topIndex)
 {}
 void Push(int x){                   //入棧
  _array[_topIndex] = x;
  _topIndex += 2;
 }
 void Pop(){                         //出棧
  _topIndex -= 2;
 }
 int Top(){                         //取得棧頂元素
  cout << _array[_topIndex - 2] << endl;
  return _array[_topIndex-2];
 }
 bool Empty(){                     //判斷棧是否爲空
  return _topIndex > _beginIndex;
 }
private:
 int* _array;
 int _topIndex;
 const int _beginIndex;
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章