1.循环队列
#include <iostream>
#include <cstring>
using namespace std;
template <typename T>
class Cir_que
{
public:
T queue[8]; //顺序表
int size_queue;//大小
int head; //队列头
int end; //队列尾
Cir_que()
{
memset(queue,0,sizeof (queue));
size_queue = 0;
head = 0;
end = 0;
}
T back()//返回最后一个元素
{
return queue[end - 1];
}
bool empty()//判空
{
return size_queue == 0 ? 1 : 0;
}
T front()//返回第一个元素
{
return queue[head];
}
void pop()//删除第一个元素
{
queue[head] = 0;
head = (head + 1) % 8;
}
void push(T c)//在末尾加入一个元素
{
if((end+1)%8 != head)
{
queue[end] = c;
end = (end + 1) % 8;
size_queue = (end + 8 - head) % 8;
}
else
{
cout << "循环队列满,不可以再次添加数据" << endl;
}
}
int size()//返回队列中的元素个数
{
size_queue = (end + 8 - head) % 8;
return size_queue;
}
};
int main()
{
Cir_que<int> t;
cout << "队列是否为空 " << t.empty() << endl;
for(int i = 1; i < 8; i++)
{
t.push(i);
}
cout << "最后一个元素是:" << t.back() << endl;
cout << "元素大小添加成功,队列大小为:" << t.size() << endl;
for(int i = 1; i < 8; i++)
{
cout << "队首元素是:" << t.front() << endl;
t.pop();
}
cout << "元素大小删除成功,队列大小为:" << t.size() << endl;
return 0;
}
2.栈
#include <iostream>
#include <cstring>
using namespace std;
template<typename T>
class Mystack
{
public:
T stack[25]; //顺序栈
int top_stack; //栈顶
int bottom_stack;//栈底
int size_stack;//大小
Mystack()//无参构造
{
memset(stack,0,sizeof(stack));
top_stack = 0;
bottom_stack = 0;
size_stack = 0;
}
T top()//栈顶元素
{
if(size_stack)
return stack[top_stack-1];
else
throw 1;
}
int size()//栈的大小
{
return size_stack;
}
bool empty()//判空
{
return size_stack == 0 ? 1 : 0;
}
void push(T c)//入栈
{
if(top_stack != 25)
{
stack[top_stack] = c;
top_stack += 1;
size_stack += 1;
}
else
{
cout << "栈满了,不可以继续添加" << endl;
}
}
void pop()//出栈
{
if(top_stack != bottom_stack)
{
top_stack -= 1;
size_stack -= 1;
}
}
};
int main()
{
Mystack<int> t;//定义栈
try
{
t.top();
cout << "默认初始值是:" << t.top() << endl;
}
catch(int)
{
cout << "此时栈为空" << endl;
cout << "栈是否为空:" << t.empty() << " 栈的大小是:" << t.size() << endl;
for(int i = 1; i <= 20; i++)//入栈
t.push(i);
cout << "入栈结束 " << "栈是否为空:" << t.empty() << " 栈的大小是:" << t.size() << endl;
for(int i = 0; i < 20; i++)//出栈
{
cout << "栈顶的元素是:" << t.top() << " 栈的大小是:" << t.size_stack << endl;
t.pop();
cout << "一个元素出栈成功" << endl;
}
cout << "出栈结束 " <<"栈是否为空:" << t.empty() << " 栈的大小是:" << t.size() << endl;
}
return 0;
}