当前位置: 首页 > news >正文

LeetCode.225. 用队列实现栈

用队列实现栈

  • 题目
  • 解题思路
    • 1. `push`
    • 2. `pop`
    • 3. `empty`
  • Code
    • Queue.h
    • Queue.c
    • Stack.c

题目

225. 用队列实现栈

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(pushtoppopempty)。

实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false

注意:

  • 你只能使用队列的标准操作 —— 也就是 push to backpeek/pop from frontsizeis empty 这些操作。

  • 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。注意:

  • 你只能使用队列的标准操作 —— 也就是 push to backpeek/pop from frontsizeis empty 这些操作。

  • 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

示例:

输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]

解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False

解题思路

使用两个队列 queue1queue2 来模拟栈的行为。队列遵循先进先出(FIFO)原则,而栈遵循后进先出(LIFO)原则,所以需要通过特定的操作来转换这种特性。

1. push

  • 目的:将元素 x 压入栈顶。
  • 思路:选择非空队列(如果两个队列都为空,则任选一个),将 x 加入该队列的尾部。

2. pop

  • 目的:移除并返回栈顶元素。
  • 思路
    • 队列是 FIFO ,栈顶元素在队列的尾部。要将除了最后一个元素之外的其他元素都移动到另一个队列中。将 nonempty 中的元素依次出队并加入到 empty 中,直到 nonempty 中只剩下一个元素,这个元素就是栈顶元素。
    • nonempty 中剩下的这个元素出队并返回。

3. empty

  • 目的:判断栈是否为空。
  • 思路:由于栈是由两个队列模拟的,当两个队列都为空时,栈才为空。所以只需要检查 queue1queue2 是否都为空即可。
    请添加图片描述

Code

Queue.h

typedef int QDataType;
typedef struct QueueNode
{
	struct QueueNode* next;
	QDataType data;
}QNode;

typedef struct Queue
{
	QNode* phead;
	QNode* ptail;
	int size;
}Queue;

void QueueInit(Queue* pq);
void QueueDestory(Queue* pq);
void QueuePush(Queue* pq, QDataType x);
void QueuePop(Queue* pq);
QDataType QueueFront(Queue* pq);
QDataType QueueBack(Queue* pq);
int QueueSize(Queue* pq);
bool QueueEmpty(Queue* pq);

Queue.c

void QueueInit(Queue* pq) {
	assert(pq);
	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
}

void QueueDestory(Queue* pq) {
	assert(pq);
	QNode* cur = pq->phead;
	while (cur) {
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}

void QueuePush(Queue* pq, QDataType x) {
	assert(pq);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL) {
		perror("malloc fail\n");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;
	if (pq->ptail == NULL) {
		assert(pq->phead == NULL);
		pq->phead = pq->ptail = newnode;
	}
	else {
		pq->ptail->next = newnode;
		pq->ptail = newnode;
	}
	pq->size++;
}

void QueuePop(Queue* pq) {
	assert(pq);
	assert(!QueueEmpty(pq));
	// one node
	if (pq->phead->next == NULL) {
		free(pq->phead);
		pq->phead = pq->ptail = NULL;
	}
	// more node
	else {
		QNode* next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}
	pq->size--;
}

QDataType QueueFront(Queue* pq) {
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->phead->data;
}
QDataType QueueBack(Queue* pq) {
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->ptail->data;
}
int QueueSize(Queue* pq) {
	assert(pq);
	return pq->size;
}
bool QueueEmpty(Queue* pq) {
	assert(pq);
	//return pq->phead == NULL && pq->ptail == NULL;
	return pq->size == 0;
}

Stack.c

typedef struct {
    Queue q1;
    Queue q2;
} MyStack;


MyStack* myStackCreate() {
    MyStack* obj = (MyStack*)malloc(sizeof(MyStack));
    if(obj == NULL){
        perror("malloc fail");
        return NULL;
    }
    QueueInit(&obj->q1);
    QueueInit(&obj->q2);
    return obj;
}

void myStackPush(MyStack* obj, int x) {
    if(!QueueEmpty(&obj->q1)){
        QueuePush(&obj->q1, x);
    }else{
        QueuePush(&obj->q2, x);
    }
}

int myStackPop(MyStack* obj) {
    Queue* pEmptyQ = &obj->q1;
    Queue* pNonEmptyQ = &obj->q2;
    if(!QueueEmpty(&obj->q1)){
        pEmptyQ = &obj->q2;
        pNonEmptyQ = &obj->q1;
    }
    while(QueueSize(pNonEmptyQ)>1){
        QueuePush(pEmptyQ,QueueFront(pNonEmptyQ));
        QueuePop(pNonEmptyQ);
    }
    int top = QueueBack(pNonEmptyQ);
    QueuePop(pNonEmptyQ);
    return top;
}

int myStackTop(MyStack* obj) {
    if(!QueueEmpty(&obj->q1)){
        return QueueBack(&obj->q1);
    }else{
        return QueueBack(&obj->q2);
    }
}

bool myStackEmpty(MyStack* obj) {
    return QueueEmpty(&obj->q1)
        && QueueEmpty(&obj->q2);
}

void myStackFree(MyStack* obj) {
    QueueDestory(&obj->q1);
    QueueDestory(&obj->q2);
    free(obj);
}

相关文章:

  • 计算机视觉算法实现——电梯禁止电瓶车进入检测:原理、实现与行业应用(主页有源码)
  • vue 入门:组件通讯
  • Python在糖尿病分类问题上寻找具有最佳 ROC AUC 分数和 PR AUC 分数(决策树、逻辑回归、KNN、SVM)
  • C++STL——容器-list(含模拟实现,即底层原理)(含迭代器失效问题)(所有你不理解的问题,这里都有解答,最详细)
  • python:audioFlux 使用教程
  • 【maxENT】最大熵模型(Maximum Entropy Model)R语言实现
  • 双系统win11 + ubuntu,如何完全卸载ubuntu系统?
  • Flutter中如何判断一个计算任务是否耗时?
  • 封装Tcp Socket
  • Pinocchio中data、model接口介绍
  • Echarts跨平台设备适配详解
  • ssh 三级跳
  • C语言中数组与指针:差异、应用及深度剖析
  • 【unity游戏开发入门到精通——UGUI】CanvasScaler画布缩放器组件
  • 探索 Go 与 Python:性能、适用场景与开发效率对比
  • MySQL中的UNION和UNION ALL【简单易懂】
  • 深入解析@Validated注解:Spring 验证机制的核心工具
  • 层归一化(Layer Normalization) vs 批量归一化(Batch Normalization)
  • mysql 有哪些存储引擎、区别是什么
  • 行星际激波在日球层中的传播:Propagation of Interplanetary Shocks in the Heliosphere (第二部分)
  • 一箭六星!力箭一号遥七运载火箭发射成功
  • 第九届非遗节将于五月下旬举办,600个非遗项目将参展参演
  • 锚定建设“中国樱桃第一县”目标,第六届澄城樱桃营销季启动
  • 央企通号建设集团有限公司原党委常委、副总经理叶正兵被查
  • 事关政府信息公开,最高法发布最新司法解释
  • 人民日报:不能层层加码,要层层负责