Problema de uso del algoritmo de Leetcode en la pila para implementar la cola

Requisitos de la asignatura

Inserte la descripción de la imagen aquí

Operación de sacar de cola

Suponiendo que hay cuatro elementos válidos 1, 2, 3, 4 almacenados en
secuencia , el orden de la pila: 4
, 3, 2, 1. Orden de salida de la cola : 1, 2, 3, 4.

En este momento, la operación pop solo puede sacar el último elemento 4 de la pila, y el primer elemento 1 de la cola es el primer elemento 1 de la cola. En este momento, podemos definir una pila secundaria nuevamente, sacar el primero 3 elementos de la pila y luego empújelos hacia la pila. Vaya a la pila secundaria y luego saque la pila principal para lograr el pop de 1, que puede considerarse como una operación de sacar de cola después de la encapsulación, diagrama:

Inserte la descripción de la imagen aquí

Enlace al tema de Leetcode: use la pila para lograr la cola

Código completo:

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
typedef int stdatatype;

typedef struct stack {
    
    
	stdatatype* data;
	int size;
	int capacity;
}stack;

//初始化
void Initstack(stack* st)
{
    
    
	if (st == NULL)
		return;
	st->data = NULL;
	st->capacity = st->size = 0;
}

//检查容量
void Checkcapacity(stack*st)
{
    
    
	if (st->size == st->capacity)
	{
    
    
		int newcapacity=st->capacity == 0 ? 1 : 2 * st->capacity;
		st->data = (stdatatype*)realloc(st->data, sizeof(stdatatype)*newcapacity);
		st->capacity = newcapacity;
	}
}

//入栈
void Stackpush(stack* st, stdatatype val)
{
    
    
	if (st == NULL)
		return;
	Checkcapacity(st);
	st->data[st->size++] = val;
}

//出栈
void Stackpop(stack* st)
{
    
    
	if (st == NULL||st->size==0)
		return;
	st->size--;
}

//获取栈中元素个数
int Satcksize(stack* st)
{
    
    
	if (st == NULL)
		return 0;
	return st->size;
}

//判断栈空
int Emptystack(stack*st)
{
    
    
	if (st == NULL || st->size == 0)
		return 1;
	else
		return 0;
}

//获取栈顶元素
stdatatype Stacktop(stack* st)
{
    
    
	return st->data[st->size - 1];
}

//销毁栈
void Destorystack(stack*st)
{
    
    
	if(st)
    {
    
    
        if(st->data)
        {
    
    
            free(st->data);
	        st->data = NULL;
	        st->size = 0;
	        st->capacity = 0;
        }
    }
}

//判断栈空
int StackEmpty(stack* st)
{
    
    
	return st->size==0;
}






typedef struct {
    
    
    struct stack pushst;    //主栈
    struct stack popst;     //副栈

} MyQueue;

/** Initialize your data structure here. */

MyQueue* myQueueCreate() {
    
    
    MyQueue*p=(MyQueue*)malloc(sizeof(MyQueue));
    Initstack(&p->pushst);
    Initstack(&p->popst);
    return p;
}

/** 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) {
    
    
    int front;
    if(!StackEmpty(&obj->popst))
    {
    
    
        front = Stacktop(&obj->popst);
        Stackpop(&obj->popst);
    }
    else
    {
    
    
        while(!StackEmpty(&obj->pushst))
        {
    
    
            Stackpush(&obj->popst,Stacktop(&obj->pushst));
            Stackpop(&obj->pushst);
        }
        front =Stacktop(&obj->popst);
        Stackpop(&obj->popst);
    }
    return front;
}

/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
    
    
    if(StackEmpty(&obj->popst))
    {
    
    
        while(!StackEmpty(&obj->pushst))
        {
    
    
            Stackpush(&obj->popst,Stacktop(&obj->pushst));
            Stackpop(&obj->pushst);
        }
        return Stacktop(&obj->popst);

    }
    else
    {
    
    
        return Stacktop(&obj->popst);
    }
}

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

void myQueueFree(MyQueue* obj) {
    
    
    Destorystack(&obj->pushst);
    Destorystack(&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_43962381/article/details/111992878
Recomendado
Clasificación