题目描述
利用两个栈模拟实现一个队列的入队和出队运算。
思路
- 首先定义一个栈的结构体
typedef struct LSNode{
int data;
struct LSNode* next;
}LSNode, *PLStack;
- 栈的特点是先进后出,队的特点是先进先出
栈1,用来存放入队的数据
栈2,用来出队,栈空则把s1中的数据出到s2中,栈不空,直接从s2出栈
bool QueuePush(PLStack s1, PLStack s2, int val){
assert(s1!= NULL && s2 != NULL);
return Push(s1, val);
}
//利用两个栈模拟出队
bool QueuePop(PLStack s1, PLStack s2, int *rtval){
assert(s1 != NULL && s2 != NULL);
int tmp;
if(IsEmpty(s2)){
while(Pop(s1, &tmp)){
Push(s2,tmp);
}
}
return Pop(s2,rtval);
}
int main(){
LSNode s1;
LSNode s2;
InitStack(&s1);
InitStack(&s2);
int tmp;
for(int i = 0; i < 10; i++){
QueuePush(&s1, &s2, i);
}
for(int i =0; i < 10; i++){
QueuePop(&s1, &s2, &tmp);
}
Destroy(&s1);
Destroy(&s2);
return 0;
}