自学内容网 自学内容网

c++9月25日

1.栈的实现

头文件

#ifndef STACKHEAD_H
#define STACKHEAD_H
#include <iostream>
#define MAX 30
using namespace std;

class Stack
{
private:
    int *ptr;
    int top;
public:
    Stack();
    Stack(int *,int);
    ~Stack();
    bool full();
    bool empty();
    int push(int);
    void show();
    Stack &operator=(const Stack &);
    int get_top();
    void pop();
};

#endif

功能函数

#include "Stackhead.h"
Stack::Stack()//无参构造
{
    this->ptr=new int [MAX];
    this->top=-1;
}
Stack::Stack(int *ptr,int top):ptr(new int [MAX]),top(-1)//有参构造
{
    this->ptr=ptr;
    this->top=top;
}
Stack::~Stack()//析构函数
{
    delete []this->ptr;
}
bool Stack::full()//判满
{
    return this->top==MAX;
}
bool Stack::empty()//判空
{
    return this->top==-1;
}
int Stack::push(int n)//入栈
{
    if(full())
    {
        cout<<"栈溢出"<<endl;
        return -1;
    }
    this->ptr[++top]=n;
    return 0;
}
void Stack::show()//遍历栈
{
     if(empty())
     {
         cout<<"空栈"<<endl;
         return;
     }
     for(int i=0;i<=this->top;i++)
     {
         cout<<this->ptr[i]<<" ";
     }
     cout<<endl;
}
Stack &Stack::operator=(const Stack &other)//赋值运算符重载
{
    for(int i=0;i<=other.top;i++)
    {
        this->push(other.ptr[i]);
    }
    return *this;
}
int Stack::get_top()//获得栈容量
{
    return this->top;
}
void Stack::pop()//出栈
{
    if(empty())
    {
        cout<<"空栈"<<endl;
        return;
    }
    this->top--;
    cout<<"出栈成功"<<endl;
}

主函数

#include "Stackhead.h"
int main()
{
   Stack s=Stack();
   int arr[5]={7,5,3,1,9};
   for(int i:arr)
   {
       s.push(i);
   }
   s.show();
   Stack s1;
   s1=s;
   s1.show();
   s1.pop();
   s1.show();
   Stack s2;
   s2.pop();
    return 0;
}

思维导图


原文地址:https://blog.csdn.net/KuaiKKyo/article/details/142533657

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!