C++动态堆栈

来源:互联网 发布:数据分析师是青春饭吗 编辑:程序博客网 时间:2024/06/15 20:01

实现一个整数堆栈,对于推入栈的整数数量无严格限制,甚至可以在计算机内存耗尽前一直推入数据。
对于这个整数堆栈,初始化时给其分配很小的内存。一旦用完堆栈空间时,就增加它的内存空间(如加倍,即New=old*2)。称这个正数堆栈为动态堆栈,该数据结构能够伸缩:对新内存的需求和维护,:回收已分配的内存。

动态堆栈看做对象,在其类中实现需求。主要要实现动态增长的内存空间,在其类中应有一个私有函数(类的客户不需要知道该函数,由这个函数由对象本身调用。),这个私有函数要实现以下功能:
(1):分配2倍于当前堆栈大小的新堆栈。
(2):将旧堆栈中的内容复制到新堆栈中的前半部分。
(3):删除旧堆栈。
(4):设置新堆栈为当前有效堆栈对象。

使用数组实现堆栈(LIFO)这种数据结构
实现过程
main.cpp

#include<iostream>#include"IStack.h"using namespace std;int main(){    IStack _stack;    for (int i = 0; i < 100; i++)        _stack.Push(i);    for (int i = 0; i < 100; i++)        cout << _stack.Pop() << endl;;    return 0;}

IStack.h

#ifndef ISTACK_H#define ISTACK_H#include <cassert>#include <iostream>const int initStack = 1;class IStack{public:    IStack();    ~IStack();    void Push(int i);//入栈    int Pop();//出栈    int Top()const;//返回栈顶元素    bool IsEmpty()const;//是否栈为空private:    void Grow();    //指向动态分配数组地址    int *_arr;    //堆栈最大容量    int _capacity;    //栈顶索引    int _top;};#endif

IStack.cpp

#include"IStack.h"IStack::IStack() :_top(0), _capacity(initStack){    _arr = new int[initStack]; //分配内存}IStack::~IStack(){    delete [] _arr; //释放内存}void IStack::Push(int i){    assert(_top <= _capacity);    if (_top == _capacity)    {        Grow();    }    _arr[_top] = i;    ++_top;}void IStack::Grow(){    std::cout << "Doubling stack from " << _capacity << ".\n";    //分配新数组    int *arrNew = new int[2 * _capacity];    //复制所有数据项    for (int i = 0; i < _capacity; ++i)    {        arrNew[i] = _arr[i];    }    _capacity *= 2;    //释放就内存    delete[]_arr;    _arr = arrNew;}int IStack::Pop(){    assert(_top > 0);    --_top;    return _arr[_top];}int IStack::Top()const{    assert(_top > 0);    return _arr[_top - 1];}bool IStack::IsEmpty()const{    assert(_top >= 0);    return _top == 0;}
0 0