LeetCode 232. Realizar cola con pila

Descripción del Título

232. Realizar cola con Stack-LeetCode (LeetCode)

Utilice solo dos pilas para implementar una cola de primero en entrar, primero en salir. La cola debe admitir todas las operaciones admitidas por las colas generales (push, pop, peek, empty):

Implemente la clase MyQueue:

• void push (int x) empuja el elemento x al final de la cola
• int pop () elimina el elemento del principio de la cola y devuelve el elemento
• int peek () devuelve el elemento al principio de la cola
• booleano vacío () devuelve si la cola está vacía verdadero; de lo contrario, devuelve falso

Descripción:

Solo puede usar operaciones de pila estándar, es decir, solo las operaciones de empujar hacia arriba, mirar / sacar desde arriba, el tamaño y las operaciones vacías son legales.
Es posible que el idioma que está utilizando no admita pilas. Puede usar list o deque (cola de dos extremos) para simular una pila, siempre que sea una operación de pila estándar.

Ejemplo 1

输入:
[“MyQueue”, “push”, “push”, “peek”, “pop”, “empty”]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]
解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

Análisis de pensamiento:

La idea de esta pregunta es similar a la idea de usar una cola
para implementar una pila. Una pila (primero en entrar, último en salir) se usa para implementar una cola (primero en entrar, primero en salir). Podemos usar dos pilas para lograr Esto. Una pila (Stack PushSt) se usa para implementar los datos en la cola. Cuando se da cuenta de la cola, solo necesita importar todos los datos en Stack PushSt a otra pila vacía (Stack PopSt), y luego directamente la pila para darse cuenta de la cola primero en entrar primero en salir

El diagrama es el siguiente:
Inserte la descripción de la imagen aquí

Código

typedef int STDataType;
typedef struct Stack
{
    
    
	STDataType* a;//动态数组
	int top;  //栈顶
	int capacity;  //容量
}Stack;
//初始化栈
void StackInit(Stack* pst);
//销毁栈
void StackDestroy(Stack* pst);
//入栈
void StackPush(Stack* pst, STDataType data);
//出栈
void StackPop(Stack* pst);
//获取栈中有效元素的个数
int StackSize(Stack* pst);
//获取栈顶元素
STDataType StackTop(Stack* pst);
//检测栈是否为空,为空返回1,非空返回0
int StackEmpty(Stack* pst);
//初始化栈
void StackInit(Stack* pst)
{
    
    
	assert(pst);
	pst->a = (STDataType*)malloc(sizeof(STDataType)* 4);
	if (pst->a == NULL)
	{
    
    
		printf("malloc fail");
	}
	pst->top = 0;
	pst->capacity = 4;
}
//销毁栈
void StackDestroy(Stack* pst)
{
    
    
	assert(pst);
	free(pst->a);
	pst->a = NULL;
	pst->top = 0;
	pst->capacity = 0;
}
//入栈
void StackPush(Stack* pst, STDataType data)
{
    
    
	assert(pst);
	//空间不够需要增容
	if (pst->top == pst->capacity)
	{
    
    
		//增容为原来的2倍
		int* tem = (STDataType*)realloc(pst->a, sizeof(STDataType)* pst->capacity * 2);
		if (tem == NULL)
		{
    
    
			printf("realloc fail");
			exit(-1);
		}
		pst->a = tem;
		pst->capacity = pst->capacity * 2;
	}
	pst->a[pst->top] = data;
	pst->top++;
}
//出栈
void StackPop(Stack* pst)
{
    
    
	assert(pst);
	//判断栈是否为空
	//相当于assert(pst->top != 0);
	assert(!StackEmpty(pst));
	pst->top--;
}
//获取栈中有效元素的个数
int StackSize(Stack* pst)
{
    
    
	assert(pst);
	//因为初始化top是0,如果初始化top是-1则返回top+1;
	return pst->top;
}
//获取栈顶元素
STDataType StackTop(Stack* pst)
{
    
    
	assert(pst);
	assert(!StackEmpty(pst));
	return pst->a[pst->top - 1];
}
//检测栈是否为空,为空返回1,非空返回0
int StackEmpty(Stack* pst)
{
    
    
	assert(pst);
	return pst->top == 0 ? 1 : 0;
}

typedef struct {
    
    
    Stack PushSt;
    Stack PopSt;
} MyQueue;

/** Initialize your data structure here. */

MyQueue* myQueueCreate() {
    
    
    MyQueue* pst = (MyQueue*)malloc(sizeof(MyQueue));
    StackInit(&pst->PushSt);
    StackInit(&pst->PopSt);
    return pst;
}

/** 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) {
    
    
    //若PopSt为空则把PushSt中的数据全部导入
    if(StackEmpty(&obj->PopSt))
    {
    
    
        while(!StackEmpty(&obj->PushSt))
        {
    
    
            StackPush(&obj->PopSt,StackTop(&obj->PushSt));
            StackPop(&obj->PushSt);
        }
    }
    //保存队头数据,返回
    int Top = StackTop(&obj->PopSt);
    StackPop(&obj->PopSt);
    return Top;
}

/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
    
    
        //若PopSt为空则把PushSt中的数据全部导入
    if(StackEmpty(&obj->PopSt))
    {
    
    
        while(!StackEmpty(&obj->PushSt))
        {
    
    
            StackPush(&obj->PopSt,StackTop(&obj->PushSt));
            StackPop(&obj->PushSt);
        }
    }
    return StackTop(&obj->PopSt);
}

/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
    
    
    return StackEmpty(&obj->PushSt) && StackEmpty(&obj->PopSt);
}

void myQueueFree(MyQueue* obj) {
    
    
    StackDestroy(&obj->PushSt);
    StackDestroy(&obj->PopSt);
    free(obj);
}

/**
 * Your MyQueue struct will be instantiated and called as such:
 * MyQueue* obj = myQueueCreate();
 * myQueuePush(obj, x);
 
 * int param_2 = myQueuePop(obj);
 
 * int param_3 = myQueuePeek(obj);
 
 * bool param_4 = myQueueEmpty(obj);
 
 * myQueueFree(obj);
*/

Supongo que te gusta

Origin blog.csdn.net/weixin_50886514/article/details/114744292
Recomendado
Clasificación