您的位置:首页 > 其它

顺序栈的实现例程

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

////////-----------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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: