This commit is contained in:
2025-07-12 23:22:19 +08:00
parent 98b0294f80
commit 321cb6c439
3 changed files with 157 additions and 0 deletions

72
src/232.c Normal file
View File

@@ -0,0 +1,72 @@
#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);
}