赞
踩
typedef struct{ int* data; int top; }MyStack; typedef struct{ MyStack* stackPush; MyStack* stackPop; }MyQueue; #define maxQueueNum 100 //队列空间 MyQueue* myQueueCreate(){ MyQueue* queue = (MyQueue*)malloc(sizeof(MyQueue)); queue->stackPush = (MyStack*)malloc(sizeof(MyStack)); queue->stackPop = (MyStack*)malloc(sizeof(MyStack)); queue->stackPush->data = (int*)malloc(sizeof(int) * maxQueueNum); queue->stackPush->top = -1; queue->stackPop->data = (int*)malloc(sizeof(int) * maxQueueNum); queue->stackPop->top = -1; return queue; } //入队 void myQueuePush(MyQueue* obj){ if((obj->stackPush->top + obj->stackPop->top) == maxStackNum - 2) //队列空间满 return ; obj->stackPush->data[++obj->stackPush->top] = x; } //出队 int myQueuePop(MyQueue* obj){ if(obj->stackPop->top != -1){ //辅助栈不为空,直接弹出 return obj->stackPop->data[obj->stackPop->top--]; } while(obj->stackPush->top != -1){ //辅助栈为空,将当前栈依次弹出并压到辅助栈中 obj->stackPop->data[++obj->stackPop->top] = obj->stackPush->data[obj->stackPush->top--]; } if(obj->stackPop->top == -1){ //辅助栈仍为空,说明对应队列为空,无值返回 return -1; } else { return obj->stackPop->data[obj->stckPop->top--]; } } //取队首值 int myQueuePeek(MyQueue* obj){ if((obj->stackPush->top == -1) && (obj->stackPop->top == -1))//队列为空 return -1; if(obj->stackPop->top != -1){ return obj->stackPop->data[obj->stackPop->top]; } else { while(obj->stackPush->top != -1){ obj->stackPop->data[++obj->stackPop->top] = obj->stackPush->data[obj->stackPush->top--]; } return obj->stackPop->data[obj->stackPop->top]; } } //判断队列是否为空 bool myQueueEmpty(MyQueue* obj){ if((obj->stackPush->top == -1) && (obj->stackPop->top == -1)) return true; else return false; } void myQueueFree(MyQueue* obj) { free(obj->stackPush->data); free(obj->stackPop->data); free(obj->stackPush); free(obj->stackPop); free(obj); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。