73 lines
1.5 KiB
C
73 lines
1.5 KiB
C
#include <solution/232.h>
|
|
#include <stdlib.h>
|
|
|
|
MyQueue *myQueueCreate()
|
|
{
|
|
MyQueue *q = (MyQueue *)malloc(sizeof(MyQueue));
|
|
q->s1 = (stack *)malloc(sizeof(stack));
|
|
q->s2 = (stack *)malloc(sizeof(stack));
|
|
|
|
q->s1->size = q->s2->size = 10;
|
|
q->s1->ptr = q->s2->ptr = 0;
|
|
|
|
q->s1->base = (int *)malloc(sizeof(int) * 10);
|
|
q->s2->base = (int *)malloc(sizeof(int) * 10);
|
|
|
|
return q;
|
|
}
|
|
|
|
void myQueuePush(MyQueue *obj, int x)
|
|
{
|
|
if (obj->s1->ptr > obj->s1->size)
|
|
{
|
|
obj->s1->base = (int *)realloc(obj->s1->base, sizeof(int) * (obj->s1->size + 10));
|
|
obj->s2->base = (int *)realloc(obj->s2->base, sizeof(int) * (obj->s1->size + 10));
|
|
obj->s1->size = obj->s2->size = obj->s1->size + 10;
|
|
}
|
|
obj->s1->base[(obj->s1->ptr)++] = x;
|
|
}
|
|
|
|
int myQueuePop(MyQueue *obj)
|
|
{
|
|
int ret;
|
|
|
|
while (obj->s1->ptr)
|
|
obj->s2->base[(obj->s2->ptr)++] = obj->s1->base[--(obj->s1->ptr)];
|
|
|
|
ret = obj->s2->base[--(obj->s2->ptr)];
|
|
|
|
while (obj->s2->ptr)
|
|
obj->s1->base[(obj->s1->ptr)++] = obj->s2->base[--(obj->s2->ptr)];
|
|
|
|
return ret;
|
|
}
|
|
|
|
int myQueuePeek(MyQueue *obj)
|
|
{
|
|
int ret;
|
|
|
|
while (obj->s1->ptr)
|
|
obj->s2->base[(obj->s2->ptr)++] = obj->s1->base[--(obj->s1->ptr)];
|
|
|
|
ret = obj->s2->base[obj->s2->ptr - 1];
|
|
|
|
obj->s1->ptr = obj->s2->ptr;
|
|
obj->s2->ptr = 0;
|
|
|
|
return ret;
|
|
}
|
|
|
|
bool myQueueEmpty(MyQueue *obj)
|
|
{
|
|
return !obj->s1->ptr;
|
|
}
|
|
|
|
void myQueueFree(MyQueue *obj)
|
|
{
|
|
free(obj->s1->base);
|
|
free(obj->s2->base);
|
|
free(obj->s1);
|
|
free(obj->s2);
|
|
free(obj);
|
|
}
|