解题图解:
1、 先用stack1存储push来的数据
2、每当要pop数据时,从stack2中取,如果 stack2为空,就先从stack1中"倒"数据到stack2。
这就是用栈实现队列的基本操作
这道题看起来比较容易,但是!如果你用C语言去去做,你还得自己去写一个栈,栈不知道写的可以看看之前的一篇文章------数据结构(C语言)------栈的两种实现方式
本题使用 动态数组构造栈
cpp
#define E int
typedef struct my_stack{
int pos;
int capcity;
E* stack;
}my_stack;
void initiaze(my_stack* mystack);
void stack_push(my_stack* mystack,E element);
void initiaze(my_stack* mystack){
mystack->pos=0;
mystack->capcity=1;
mystack->stack=(E*)malloc(sizeof(E));
}
void stack_push(my_stack* mystack,E element){
if(mystack->pos==mystack->capcity){//扩容
mystack->capcity *= 2;
mystack->stack=(E*)realloc(mystack->stack,(mystack->capcity)*sizeof(E));
}
mystack->stack[mystack->pos]=element;
mystack->pos++;
}
typedef struct {
my_stack* stack1;
my_stack* stack2;
} MyQueue;
MyQueue* myQueueCreate() {
my_stack* s1=(my_stack*)malloc(sizeof(my_stack));
my_stack* s2=(my_stack*)malloc(sizeof(my_stack));
initiaze(s1);
initiaze(s2);
MyQueue* my_queue = (MyQueue*)malloc(sizeof(MyQueue));
my_queue->stack1=s1;
my_queue->stack2=s2;
return my_queue;
}
void myQueuePush(MyQueue* obj, int x) {
stack_push(obj->stack1,x);
}
int myQueuePop(MyQueue* obj) {
if(obj->stack2->pos==0){
while(obj->stack1->pos){
stack_push(obj->stack2,obj->stack1->stack[obj->stack1->pos-1]);
obj->stack1->pos--;
}
}
E ele= obj->stack2->stack[obj->stack2->pos-1];
obj->stack2->pos--;
return ele;
}
int myQueuePeek(MyQueue* obj) {
if(obj->stack2->pos==0){
while(obj->stack1->pos){
stack_push(obj->stack2,obj->stack1->stack[obj->stack1->pos-1]);
obj->stack1->pos--;
}
}
return obj->stack2->stack[obj->stack2->pos-1];
}
bool myQueueEmpty(MyQueue* obj) {
if(obj->stack2->pos==0 && obj->stack1->pos==0)return true;
return false;
}
void myQueueFree(MyQueue* obj) {
free(obj->stack1->stack);
free(obj->stack2->stack);
free(obj->stack1);
free(obj->stack2);
free(obj);
}