用栈实现队列

时间:2019-01-10
本文章向大家介绍用栈实现队列,主要包括用栈实现队列使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();

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;
}