题目描述和思路
各个接口函数的实现(注释详细)
typedef struct
{
Queue q1;
Queue q2;
} MyStack;
MyStack* myStackCreate()
{
MyStack* obj=(MyStack*)malloc(sizeof(MyStack));
assert(obj);
QueueInit(&obj->q1);
QueueInit(&obj->q2);
return obj;
}
void myStackPush(MyStack* obj, int x)
{
if(!QueueEmpty(&obj->q1))
{
QueuePush(&obj->q1,x);
}
else
{
QueuePush(&obj->q2,x);
}
}
int myStackPop(MyStack* obj)
{
Queue* empty=&obj->q1;
Queue* nonempty=&obj->q2;
if(!QueueEmpty(&obj->q1))
{
nonempty=&obj->q1;
empty=&obj->q2;
}
while(QueueSize(nonempty)>1)
{
int top=QueueFront(nonempty);
QueuePush(empty,top);
QueuePop(nonempty);
}
int top=QueueFront(nonempty);
QueuePop(nonempty);
return top;
}
int myStackTop(MyStack* obj)
{
Queue* empty=&obj->q1;
Queue* nonempty=&obj->q2;
if(!QueueEmpty(&obj->q1))
{
nonempty=&obj->q1;
empty=&obj->q2;
}
return QueueBack(nonempty);
}
bool myStackEmpty(MyStack* obj)
{
if(QueueEmpty(&obj->q1)&&QueueEmpty(&obj->q2))
return true;
else
return false;
}
void myStackFree(MyStack* obj)
{
QueueDestroy(&obj->q1);
QueueDestroy(&obj->q2);
free(obj);
}
|