首先明白两个概念
栈:先入后出
队列:先入先出
队1操作:入数据
队2操作:若队列1 2都不为空从将队列1中除队尾元素全部移至队列2 队列1对头出
若队列2为空 将队列1中除队尾元素全部移至队列2 队列1对头出
若队列1为空 将队列2中除队尾元素全部移至队列1 队列2对头出
总结可得:当队1 为空时 需要将队列2中除队尾元素全部移至队列1 队列2对头出
队1不为空时,将队列1中除队尾元素全部移至队列2 队列1对头出
结构体定义
typedef struct TQTStack
{
Queue q1;
Queue q2;
}TQTStack, * PTQTStack;
初始化
void my_Init_Stack(PTQTStack ps){
assert(ps != NULL);
Init_queue(&ps->q1);
Init_queue(&ps->q2);
}
调用队列初始化操作即可
入栈
bool my_Push(PTQTStack ps, ELEM_TYPE val) {
assert(ps != NULL);
return Push(&ps->q1, val);
}
数据全部入队1
出栈
bool my_Pop(PTQTStack ps, ELEM_TYPE* rtval) {
assert(ps != NULL);
if (my_IsEmpty(ps)) {
return false;
}
if (IsEmpty(&ps->q1)) { //队1为空时
int size = Get_length(&ps->q2);
while (size > 1) {
int temp;
Pop(&ps->q2, &temp);
Push(&ps->q1, temp);
size--;
} //将队2数据压入队1,直至队2剩余一个,出队2最后一个元素
Pop(&ps->q2, rtval);
}
else { //队1不为空时
int size = Get_length(&ps->q1);
while (size > 1) {
int temp;
Pop(&ps->q1, &temp);
Push(&ps->q2, temp);
size--;
} //将队1数据压入队2,直至队2剩余一个,出对1最后一个元素
Pop(&ps->q1, rtval);
}
return true;
}
若出栈成功用rtval接收 出队成功的值
获取栈顶元素
bool my_my_Top(PTQTStack ps, ELEM_TYPE* rtval) {
assert(ps != NULL);
if (my_IsEmpty(ps)) {
return false;
}
if (IsEmpty(&ps->q1)) {
int size = Get_length(&ps->q2);
while (size > 1) {
int temp;
Pop(&ps->q2, &temp);
Push(&ps->q1, temp);
size--;
}
Top(&ps->q2, rtval);
}
else {
int size = Get_length(&ps->q1);
while (size > 1) {
int temp;
Pop(&ps->q1, &temp);
Push(&ps->q2, temp);
size--;
}
Top(&ps->q1, rtval);
}
return true;
}
与出栈操作类似,若操作成功需要用 rtval 接收栈顶元素值
其他函数
//获取有效数据个数
int my_Get_length(PTQTStack ps) {
return Get_length(&ps->q1) + Get_length(&ps->q2);
}
//判空
bool my_IsEmpty(PTQTStack ps) {
if (IsEmpty(&ps->q1) && IsEmpty(&ps->q2)) {
return true;
}
return false;
}
判满
//bool my_IsFull(PTQTStack ps); //此处为链式队列不需要判满
//清空
void my_Clear(PTQTStack ps) {
Clear(&ps->q1);
Clear(&ps->q2);
}
//销毁
void my_Destroy(PTQTStack ps) {
Destroy(&ps->q1);
Destroy(&ps->q2);
}
//打印
void my_Show(PTQTStack ps) {
assert(ps != NULL);
Show(&ps->q1);
Show(&ps->q2);
}
*打印函数只是获取了栈(两个队列)的值,并没有按照出栈顺序依次打印