顺序栈的实现例程

说明:一直对栈似是而非的理解,因此写出其实现,但是就这个简单的程序中,我发现存在着很多缺陷,谁有兴趣帮我更正,本人非常感谢。另外我发现仅就顺序栈而言,都存在着多个变种:)

-----------Stack_Seq_SelfDefine.h-----------///

#include <iostream>
using namespace std;

//-----------------------------------------//
// Stack -- Sequence, SelfDefine
// SuperXu 2006.11
// Version: Final
//-----------------------------------------//

class SSS {
private:
 static const int INITSIZE;
 static const int INCREAMENT;
 int* m_base;
 int* m_top;
 int m_stack_size;
public:
 SSS(int sz = INITSIZE) : m_stack_size(sz) {
  m_base = new int[sz];
  m_top = m_base;
 }

 SSS(const SSS& sss) {
  int* new_base = new int[sss.m_stack_size];
  int* p = sss.m_base;
  
  m_base = new_base;  
  while (p < sss.m_top)
  {
   *new_base = *p;
   ++new_base;
   ++p;
  }
  m_top = new_base;
 }

 SSS& operator =(const SSS& sss) {
  if (this == &sss)
   return *this;
  delete m_base;
  int* new_base = new int[sss.m_stack_size];
  int* p = sss.m_base;
  
  m_base = new_base;  
  while (p < sss.m_top)
  {
   *new_base = *p;
   new_base++;
   p++;
  }
  m_top = new_base;
  return *this;
 }

 ~SSS() {
  delete[] m_base;
 }

 bool isEmpty() const {
  return (m_base == m_top);
 }
 int getTop() const
 {
  if (m_top == m_base)
   return -1;
  return *(m_top-1);
 }

 void push(const int& value);
 int pop();

 int Number() const {
  return (m_top - m_base);
 }

 void display() const
 {
  int* p = m_top;
  while (p != m_base)
  {
   p--;
   cout << *p << "  ";
  }
  cout << endl;
 }

};  

///--------Stack_Seq_SelfDefine.cpp--------

#include "Stack_Seq_SelfDefine.h"

const int SSS::INITSIZE = 10;
const int SSS::INCREAMENT = 5;

void SSS::push(const int& value)
{
 if (m_top - m_base >= m_stack_size)  //increase memory
 {
  int* new_base = new int[m_stack_size + INCREAMENT];
  int* p = m_base;
  
  m_base = new_base;  
  while (p < m_top)
  {
   *new_base = *p;
   new_base++;
   p++;
  }
  m_top = new_base;
  m_stack_size += INCREAMENT;
 }
 *m_top = value;
 m_top++;
}

int SSS::pop()
{
 if (m_base == m_top)
  return -1;
 return *(--m_top); 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值