typedef int TypeData;
typedef struct QueueNode
{
TypeData val;
struct QueueNode* next;
}QueueNode;
typedef struct Queue
{
QueueNode* head;
QueueNode* tail;
}Queue;
void QueueInit(Queue* pq)
{
assert(pq);
pq->head = NULL;
pq->tail = NULL;
}
void QueuePush(Queue* pq, TypeData x)
{
assert(pq);
QueueNode* node = (QueueNode*)malloc(sizeof(QueueNode));
assert(node);
node->val = x;
node->next = NULL;
if (pq->head == NULL)
{
pq->head = node;
pq->tail = pq->head;
return;
}
pq->tail->next = node;
pq->tail = pq->tail->next;
}
TypeData QueueFront(Queue* pq)
{
assert(pq);
assert(pq->head);
return pq->head->val;
}
void QueuePop(Queue* pq)
{
assert(pq);
assert(pq->head && pq->tail);
if (pq->head->next == NULL)
{
free(pq->head);
pq->head = NULL;
pq->tail = NULL;
return;
}
QueueNode* headNext = pq->head->next;
free(pq->head);
pq->head = headNext;
}
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->head == NULL;
}
void QueueDestroy(Queue* pq)
{
assert(pq);
QueueNode* cur = pq->head;
while (cur != NULL)
{
QueueNode* next = cur->next;
free(cur);
cur = next;
}
pq->head = NULL;
pq->tail = NULL;
free(pq);
}
typedef struct {
Queue* q1;
Queue* q2;
} MyStack;
MyStack* myStackCreate() {
MyStack* obj = (MyStack*)malloc(sizeof(MyStack));
assert(obj);
obj->q1 = (Queue*)malloc(sizeof(Queue));
obj->q2 = (Queue*)malloc(sizeof(Queue));
QueueInit(obj->q1);
QueueInit(obj->q2);
return obj;
}
void myStackPush(MyStack* obj, int x) {
assert(obj);
if (!QueueEmpty(obj->q1))
{
QueuePush(obj->q1, x);
}
else
{
QueuePush(obj->q2, x);
}
}
int myStackPop(MyStack* obj) {
assert(obj);
TypeData val = 0;
if (!QueueEmpty(obj->q1))
{
while (!QueueEmpty(obj->q1))
{
val = QueueFront(obj->q1);
QueuePop(obj->q1);
if (!QueueEmpty(obj->q1))
{
QueuePush(obj->q2, val);
}
}
return val;
}
if (!QueueEmpty(obj->q2))
{
while (!QueueEmpty(obj->q2))
{
val = QueueFront(obj->q2);
QueuePop(obj->q2);
if (!QueueEmpty(obj->q2))
{
QueuePush(obj->q1, val);
}
}
return val;
}
return val;
}
int myStackTop(MyStack* obj) {
assert(obj);
TypeData val = 0;
if (!QueueEmpty(obj->q1))
{
while (!QueueEmpty(obj->q1))
{
val = QueueFront(obj->q1);
QueuePop(obj->q1);
QueuePush(obj->q2, val);
}
return val;
}
if (!QueueEmpty(obj->q2))
{
while (!QueueEmpty(obj->q2))
{
val = QueueFront(obj->q2);
QueuePop(obj->q2);
QueuePush(obj->q1, val);
}
return val;
}
return val;
}
bool myStackEmpty(MyStack* obj) {
return QueueEmpty(obj->q1) && QueueEmpty(obj->q2);
}
void myStackFree(MyStack* obj) {
assert(obj);
QueueDestroy(obj->q1);
QueueDestroy(obj->q2);
free(obj);
}