欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > C++ 学习 2024.9.3

C++ 学习 2024.9.3

2024/10/24 18:22:17 来源:https://blog.csdn.net/m0_68948389/article/details/141869836  浏览:    关键词:C++ 学习 2024.9.3

封装栈与队列

栈:

#include <iostream>using namespace std;class Stack
{
private:int *a;      //动态数组存储元素int size;    //栈容量int top;   //栈顶元素索引
public://有参构造Stack(int size):size(size),top(-1){a=new int[size];}//析构~Stack(){delete[]a;}//判空bool empty(){return top==-1;}//入栈void push_in(int const &e){if(top+1==size)  //二倍扩容{int *newa=new int[size*2];for(int i=0;i<size;++i){newa[i]=a[i];}delete[]a;a=newa;size*=2;}a[++top]=e;}//出栈void pop(){if(empty()){cout<<"栈为空,出栈失败"<<endl;}else{--top;}}//栈内元素个数int size_1(){if(empty())  //栈空{return 0;}return top+1;}//访问栈顶元素void at_top(){if(!empty()){cout<<"栈顶元素为:"<<a[top]<<endl;}else{cout<<"栈为空"<<endl;}}//展示函数void show(){cout<<"栈内元素为"<<endl;for(int i=0;i<=top;i++){cout<<a[i]<<" ";}cout<<endl;}
};int main()
{Stack s(10);s.push_in(5);s.push_in(2);s.push_in(0);s.show();             //5 2 0int count=s.size_1();cout<<"栈内元素个数为:"<<count<<endl;s.push_in(9); s.show();           //5 2 0 9s.pop();cout<<"执行一次pop函数后"<<endl;s.show();          //5 2 0s.at_top();   //访问栈顶元素s.pop();s.pop();s.pop();   //此时栈为空s.pop();return 0;
}

队列:

#include <iostream>using namespace std;
int count=0;
class Queue
{
private:int *a;     //动态数组存储int size;    //队列容量int front;   //队头元素索引int last;  //队尾元素索引
public://有惨构造Queue(int size):size(size),front(0),last(0){a=new int[size];}//析构函数~Queue(){delete []a;}//判空bool empty(){return front==last;}//访问队头元素void at_front(){if(empty()){cout<<"队列为空"<<endl;}else{cout<<"队头元素为:"<<a[front]<<endl;}}//访问队尾元素void at_last(){if(empty()){cout<<"队列为空"<<endl;}else{cout<<"队尾元素为:"<<a[(last+size-1)&size]<<endl;}}//队列中元素个数int size_1(){if(empty())  //栈空{return 0;}return last-front;}//向队尾插入元素void push_in(int const &e){if((last+1)%size==front)   //二倍扩容{int *newa=new int[size*2];for(int i=0;i<size;++i){newa[i]=a[(front+i)&size];}delete []a;a=newa;size*=2;front=0;last=size/2;}a[last]=e;last=(last+1)%size;count++;}//删除首个元素void pop(){if(empty()){cout<<"队列为空"<<endl;}else{front++;front%=size;}}//展示函数void show(){if(empty()){cout<<"队列为空"<<endl;}else{cout<<"队列中元素为:"<<"";for(int i=front;i<count;i++){cout<<a[i]<<" ";}cout<<endl;}}
};int main()
{Queue q(10);q.push_in(1);q.push_in(3);q.push_in(1);q.push_in(4);q.show();       //1 3 1 4int haha=q.size_1();cout<<"队列中元素个数为:"<<haha<<endl;   //4q.pop();cout<<"执行一次pop函数后"<<endl;q.show();  //3 1 4q.at_front();q.at_last();    //访问队尾元素一直显示0  抓耳挠腮仍无法解决return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com