스 택 으로 대기 열 구현
19578 단어 데이터 구조
queue.push(1); queue.push(2); queue.peek(); // 1 queue. pop (); /1 queue. empty (); /false 로 돌아 가기
typedef int STDatatype;
typedef struct Stack
{
STDatatype* _a;
int _top;//
int _capacity;//
}Stack;
void StackInit(Stack* ps,int n)
{
assert(ps);
ps->_a = NULL;
ps->_capacity = 0;
ps->_top = 0;
}
void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->_a);
ps->_a = NULL;
ps->_capacity = 0;
ps->_top = 0;
}
void StackPush(Stack* ps, STDatatype x)
{
assert(ps);
if (ps->_top == ps->_capacity)
{
size_t newcapacity = ps->_capacity == 0 ? 4 : ps->_capacity * 2;
ps->_a = (STDatatype*)realloc(ps->_a, sizeof(STDatatype)*newcapacity);
assert(ps->_a);
ps->_capacity = newcapacity;
}
ps->_a[ps->_top] = x;
ps->_top++;
}
void StackPop(Stack* ps)
{
assert(ps);
if(ps->_top > 0)
{
ps->_top--;
}
}
STDatatype StackTop(Stack* ps)
{
assert(ps);
return ps->_a[ps->_top - 1];
}
int StackEmpty(Stack* ps)
{
assert(ps);
return ps->_top == 0 ? 0 : 1;
}
int StackSize(Stack* ps)
{
assert(ps);
return ps->_top;
}
typedef struct {
Stack pushST;
Stack popST;
} MyQueue;
/** Initialize your data structure here. */
MyQueue* myQueueCreate(int maxSize) {
MyQueue* queue = (MyQueue*)malloc(sizeof(MyQueue));
StackInit(&queue->pushST,maxSize);
StackInit(&queue->popST,maxSize);
return queue;
}
/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {
StackPush(&obj->pushST,x);
}
/** Removes the element from in front of queue and returns that element. */
int myQueuePop(MyQueue* obj) {
if(StackEmpty(&obj->popST) == 0)
{
while(StackEmpty(&obj->pushST) != 0)
{
StackPush(&obj->popST,StackTop(&obj->pushST));
StackPop(&obj->pushST);
}
}
int front = StackTop(&obj->popST);
StackPop(&obj->pushST);
return front;
}
/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
if(StackEmpty(&obj->popST) == 0)
{
while(StackEmpty(&obj->pushST) != 0)
{
StackPush(&obj->popST,StackTop(&obj->pushST));
StackPop(&obj->pushST);
}
}
return StackTop(&obj->popST);
}
/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
if(StackEmpty(&obj->pushST) == 0 && StackEmpty(&obj->popST) == 0)
return true;
else
return false;
}
void myQueueFree(MyQueue* obj) {
StackDestroy(&obj->pushST);
StackDestroy(&obj->popST);
free(obj);
obj = NULL;
}