数组实现一定大小的栈结构
用数组实现一定大小的栈,栈是先进后出的结构,这个实现起来比较简单。直接看程序即可。
#include <iostream>
using namespace std;
#define NUM 5 //栈大小
//声明一个类
class Mystack{
private: //私有变量
int *array;
int idx;
int N;
public:
Mystack(int N);
~Mystack();
void push(int element);
int pop();
int peek();
void printstack();
};
Mystack::Mystack(int N)
{
this ->N = N;
array = new int[N];
idx = 0;
}
Mystack::~Mystack()
{
delete[] this ->array;
}
void Mystack::push(int element) // 压栈
{
if(idx == N)
cout<<"The stack is full!"<<endl;
else
array[idx ++] = element;
}
int Mystack::pop() //出栈
{
if(idx == 0)
{
cout<<"The stack is null!"<<endl;
}
else
return array[--idx];
}
int Mystack::peek() //取出栈顶元素 但注意栈没有变
{
if(idx == 0)
{
cout << "The peek is null" <<endl;
return -1;
}
else
return array[idx -1];
}
void Mystack::printstack() //打印
{
for(int i = 0; i < N; i ++)
{
cout << array[i] <<" ";
}
cout << endl;
}
int main(int argc, char** argv) {
Mystack stack1(NUM); //栈大小
stack1.push(1); //压栈
stack1.push(3);
stack1.push(6);
stack1.push(10);
stack1.push(15);
stack1.printstack();
for( int i = 0; i < 5; i ++)
{
cout << "pop element is " << stack1.pop() << endl; // 出栈
cout << "peek element is " << stack1.peek() << endl; //看栈顶元素
cout << endl;
}
stack1.printstack();
return 0;
}
数组实现一定大小的队列
用数组实现一定大小的队列,栈是先进先出的结构,这个实现起来也比较简单。直接看程序即可。
#include <iostream>
using namespace std;
#define NUM 5 //栈大小
//声明一个类
class MyQue{
private: //私有变量
int *array;
int start;
int end;
int size;
int len;
public:
MyQue(int N);
~MyQue();
void push(int element);
int poll();
int peek();
void printque();
};
MyQue::MyQue(int N)
{
size = 0;
start = 0;
end = 0;
len = N;
array = new int[len];
}
MyQue::~MyQue()
{
delete[] array;
}
void MyQue::push(int element) // 入队
{
if(end == len)
cout<<"The Que is full!"<<endl;
size ++;
array[end] = element;
end = end == len - 1 ? 0 : end + 1; //判断还有没有空间
}
int MyQue::poll() //出队
{
if(size == 0)
{
cout<<"The size is null!"<<endl;
}
size --;
int tmp = start;
start = start == len - 1 ? 0 : start + 1;
return array[tmp];
}
int MyQue::peek() //取出队顶元素 但注意队没有变
{
if(size == 0)
{
cout << "The peek is null" <<endl;
return -1;
}
else
return array[start];
}
void MyQue::printque() //打印
{
for(int i = 0; i < len; i ++)
{
cout << array[i] <<" ";
}
cout << endl;
}
int main(int argc, char** argv) {
MyQue que1(NUM); //队列大小
que1.push(1); //入队
que1.push(2);
que1.push(3);
que1.push(4);
que1.push(15);
que1.printque();
for( int i = 0; i < 5; i ++)
{
cout << "pop element is " << que1.poll() << endl; // 出队
cout << "peek element is " << que1.peek() << endl; //看队列顶元素
cout << endl;
}
que1.printque();
return 0;
}