本文主要是介绍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;
}
这篇关于C++ 学习 2024.9.3的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!