C++实现顺序栈

近期在学习C++ 的过程,由于时间仓促,基本知识未能及时整理(后期补充),为了巩固所学的知识,用C++语言来实现顺序栈。基本代码如下:

/*
** 题目:实现顺序栈
*/

#include<iostream>
#include<cstring>
#include <stdlib.h>
#include <time.h>  
using namespace std;

class SqStack
{
private:
    int *_pstack;
    int _top;
    int _size;
    void resize()
    {
        int *ptmp = new int[_size * 2];
        memcpy(ptmp, _pstack, sizeof(int)*_size);
        _size *= 2;
        delete[]_pstack;
        _pstack = ptmp;
    }
public:
    SqStack(int size = 10)
    {
        _pstack = new int[size];
        _top = 0;
        _size = size;
    }
    ~SqStack()
    {
        delete[]_pstack;
        _pstack = NULL;
    }
    SqStack(const SqStack &src)     //自定义构造函数,防止浅拷贝的事情发生
    {
        _pstack = new int[src._size];
        memcpy(_pstack, src._pstack, sizeof(int)*src._top);
        _top = src._top;
        _size = src._size;
    }
    void operator=(const SqStack &src)    //自定义赋值函数,防止浅拷贝的事情发生
    {
        if (this == &src)
            return;
        delete[]_pstack;
        _pstack = new int[src._size];
        memcpy(_pstack, src._pstack, sizeof(int)*src._top);
        _top = src._top;
        _size = src._size;
    }
    void push(int val)
    {
        if (full())
            resize();
        _pstack[_top++] = val;
    }
    void pop()
    {
        if (empty())
            return;
        _top--;
    }
    int top()
    {
        return _pstack[_top - 1];
    }
    bool empty()
    {
        return _top == 0;  // !_top;
    }
    bool full()
    {
        return _top == _size;
    }
    //打印栈内元素;
    void print()
    {
        for (int i = 0; i <_top; i++)
        {
            cout << _pstack[i] << "\t";
            if ((i + 1) % 5 == 0)
                cout << endl;
        }
        cout << endl;
    }

};

int main()
{
    cout << "顺序栈基本操作" << endl;
    SqStack sqstack(5);     //构造函数
    srand((unsigned)time(NULL));
    for (int i = 0; i < 5; i++)
    {
        sqstack.push(rand());    //入栈函数
    }
    sqstack.print();  //打印函数
    sqstack.push(rand()); //入栈函数   中间包含一次扩容
    sqstack.push(rand()); //入栈函数   中间包含一次扩容
    sqstack.print();
    cout << "出栈元素" << endl;
    sqstack.pop();
    sqstack.print();  //打印函数
    printf("栈顶元素是:%d\n", sqstack.top());

    cout << "调用自定义拷贝构造函数" << endl;
    //自定义拷贝构造函数
    SqStack sqstackTwo(sqstack);
    sqstackTwo.print();


    cout << "调用自定义赋值函数" << endl;
    SqStack sqstackThree;
    sqstackThree = sqstackTwo;
    sqstackThree.push(rand());
    sqstackThree.print();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u013266600/article/details/78397136
今日推荐