232.用栈实现队列
大家可以先看视频,了解一下模拟的过程,然后写代码会轻松很多。
题目链接/文章讲解/视频讲解:代码随想录
代码如下
typedef struct {
int stackintop ; //设置进栈头指针
int stackouttop ; //设置出栈头指针
int stackin[100] ; //设置进栈数组
int stackout[100] ; //设置出栈数组
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* queue = ( MyQueue*)malloc(sizeof(MyQueue));
queue->stackintop = 0 ; //将进栈指针设为0
queue->stackouttop = 0 ; //将出栈指针设为0
return queue ;
}
void myQueuePush(MyQueue* obj, int x) {
obj->stackin[obj->stackintop] = x ;
obj->stackintop++ ;
}
int myQueuePop(MyQueue* obj) {
int stackintop = obj->stackintop ; //重新定义两个指针,复制出栈和进栈头指针
int stackouttop = obj->stackouttop ;
if(stackouttop == 0){ //如果出栈数组等于0 则说明出栈数组为空
while(stackintop > 0){ //如果进栈数组大于0 ,说明进栈数组里有元素
stackintop--; //因为进栈数组的元素下标为0-(stackintop-1),进栈数组元素个数为
//stackintop个,所以先将进栈头指针-1
obj->stackout[stackouttop] = obj->stackin[stackintop] ; //再将进栈数组的元素赋给
//出栈头指针
//此时的出栈头指针是0
//赋值操作结束出栈头指+1
stackouttop++ ; //当stackintop值为0时跳出循环
}
}
stackouttop-- ; //同理出栈数组个数为 stackouttop个,最大下标为
// stackouttop-1
int tmp = obj->stackout[stackouttop]; //将最顶元素赋给一个临时变量
while(stackouttop > 0 ){ //用同样的方法将出栈数组赋值给进栈数组
stackouttop--;
obj->stackin[stackintop] = obj->stackout[stackouttop];
stackintop++;
}
obj->stackintop = stackintop ;
obj->stackouttop = stackouttop ;
return tmp ;
}
int myQueuePeek(MyQueue* obj) { //队列开头元素为进栈数组最底层元素
return obj->stackin[0];
}
bool myQueueEmpty(MyQueue* obj) { //如果两个指针都是0 则队列为空
if(obj->stackintop == 0 && obj->stackouttop == 0 ){
return true ;
}else{
return false ;
}
}
void myQueueFree(MyQueue* obj) {
obj->stackintop = 0 ;
obj->stackouttop = 0 ;
}
感想: 设置两个栈的想法没有想到,看了卡哥的视频,把思路理解了其实这道题的具体实现并没有特别特别难。但是就是要注意数组的下标问题
225. 用队列实现栈
可以大家惯性思维,以为还要两个队列来模拟栈,其实只用一个队列就可以模拟栈了。
建议大家掌握一个队列的方法,更简单一些,可以先看视频讲解
题目链接/文章讲解/视频讲解:代码随想录
代码如下
可以用数组做
typedef struct {
int queue[100] ;
int front ;
int rear ;
}MyStack ;
MyStack* myStackCreate(){
MyStack* stack = (MyStack*)malloc(sizeof( MyStack));
stack->front = 0 ;
stack->rear = 0 ;
return stack ;
}
void myStackPush(MyStack* obj, int x) {
obj->queue[(obj->rear)] = x ;
obj->rear++ ;
}
int myStackPop(MyStack* obj) {
int front = obj->front ;
int rear = obj->rear ;
int size = rear-front ;
size-- ;
while(size-- ){
obj->queue[rear] = obj->queue[front]; //这是最关键的一步,把元素弹出在放回去
front++;
rear++;
}
int top = obj->queue[front];
front++;
obj->front = front ;
obj->rear =rear ;
return top ;
}
int myStackTop(MyStack* obj) {
return obj->queue[(obj->rear)-1] ;
}
bool myStackEmpty(MyStack* obj) {
return obj->rear == obj->front ;
}
void myStackFree(MyStack* obj) {
obj->front = 0 ;
obj->rear = 0 ;
}