2019C++期末复习①——数组/堆栈/队列
整理一下笔记 如果有错误告诉我一下下
一,数组
#include<iostream>
using namespace std;
class myarr//数组
{
int a[100];
int s;
public:
myarr()
{
s = 0;
}
int push_back(int n)//放入
{
if (s == 100)
return -1;
a[s] = n;
s++;
return 0;
}
int get(int i)//取出
{
if(s>0)//如果s==0,说明没往里面放东西
{
return a[i-1];//从i=1开始
}
else
{
return 0;
}
}
int dele(int i)//删除
{
if (s == 0||i>s)
return -1;
for(;i<s;i++)
{
a[i - 1] = a[i];
}
s--;
return 0;
}
int size()//返回数组长度
{
return s;
}
};
int main()
{
myarr *ma;
ma = new myarr();//开的指针 用箭头 要new
ma->push_back(78);
ma->push_back(79);
ma->push_back(80);
ma->push_back(81);
ma->push_back(82);
int k = ma->size();
for(int i=1;i<=k;i++)
cout << ma->get(i)<<endl;
}
显示结果
78
79
80
81
82
二,堆栈
#include<iostream>
using namespace std;
class mystack//先进的后出
{
int a[100];
int s;
public:
mystack()
{
s = 0;
}
int push_back(int n)
{
if (s == 100)
return -1;
a[s] = n;
s++;
return 0;
}
void pop()//弹栈
{
s--;
}
int top()//取栈顶,即取最后一个
{
return a[s - 1];
}
int size()//
{
return s;
}
};
int main()
{
mystack *ma;
ma = new mystack();
ma->push_back(78);
ma->push_back(79);
ma->push_back(80);
ma->push_back(81);
ma->push_back(82);
cout << ma->top();
}
显示结果
82
三,队列
#include<iostream>
using namespace std;
class queque// 头删尾进 先进的先出
{ int a[100];
int front;//头
int rear;//尾
public:
queque()
{
front = 0; rear = 0;
}
int push_back(int n)//加 尾
{
if (rear == 100)
return -1;
a[rear] = n;
rear++;
return 0;
}
void pop()//删 头
{
front++;
}
int top()//取头
{
return a[front];
}
int size()//长度
{
return rear-front;//不用+1,在放的时候rear就自加1
}
};
int main()
{
queque *ma;
ma = new queque();
ma->push_back(78);
ma->push_back(79);
ma->push_back(80);
ma->push_back(81);
ma->push_back(82);
ma->pop();
cout << ma->top()<<endl<<ma->size();
}
显示结果
79
4