力扣:用栈实现队列、用队列实现栈

代码随想录打卡9

前言:
跳过哈希表直接开栈与队列的题目,这两道题比较考验对栈和队列的基本操作。用栈实现队列代码有点懵,好多基础代码都忘记了,还有栈的初始化创建。

用栈实现队列

题目:
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false

思路:
这里使用两个栈来实现队列的基本操作。
这里对于栈的创建有点迷,以前使用栈没有malloc过。

具体步骤和注释见代码

typedef struct {
    int stackInTop, stackOutTop;
    int stackIn[100], stackOut[100];
} MyQueue;

MyQueue* myQueueCreate() {
    MyQueue * queue = (MyQueue*)malloc(sizeof(MyQueue));
    queue->stackInTop = 0;
    queue->stackOutTop = 0;
    return queue;
}   

void myQueuePush(MyQueue* obj, int x) {
   obj->stackIn[(obj->stackInTop)++] = x;
}

int myQueuePop(MyQueue* obj) {
    int stackInTop = obj->stackInTop;//优化:复制栈顶指针,减少对内存的访问次数
    int stackOutTop = obj->stackOutTop;
    //若输出栈为空
    if(stackOutTop == 0){
        while(stackInTop >0){//将第一个栈中元素复制到第二个栈中
            obj->stackOut[stackOutTop++] = obj->stackIn[--stackInTop];
        }
    }
    //将第二个栈中栈顶元素(队列的第一个元素)出栈,并保存
    int top = obj->stackOut[--stackOutTop];
    while(stackOutTop >0){//将输出栈中元素放回输入栈中
        obj->stackIn[stackInTop++] = obj->stackOut[--stackOutTop];
    }
    //更新栈顶指针
    obj->stackInTop = stackInTop;
    obj->stackOutTop = stackOutTop;
    //返回队列中第一个元素
    return top;
}

int myQueuePeek(MyQueue* obj) {
    return obj->stackIn[0];//返回输入栈中的栈底元素
}

bool myQueueEmpty(MyQueue* obj) {
    if(obj->stackInTop == 0 && obj->stackOutTop == 0)
        return 1;
    else
        return 0;    
}

void myQueueFree(MyQueue* obj) {
    obj->stackInTop = 0;
    obj->stackOutTop = 0;
}


用队列实现栈

题目:
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。

实现 MyStack 类:

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

思路:参考上题的代码编写后,本题比较简单,但有编写时出现过很多语法错误,都在debug后提交通过了。
只需要用一个队列即可实现。

typedef struct {
    int rear;
    int front;
    int data[100];
} MyStack;


MyStack* myStackCreate() {
    MyStack * stack = (MyStack*)malloc(sizeof(MyStack));
    stack->rear = 0;
    stack->front = 0;
    return stack;
}

void myStackPush(MyStack* obj, int x) {
    obj->data[(obj->rear)++] = x;
}

int myStackPop(MyStack* obj) {
    //if(obj->rear > 0){
        int top = obj->data[--(obj->rear)];
        return top;
   // }

}

int myStackTop(MyStack* obj) {
    int top = obj->data[(obj->rear)-1];
    
    return top;
}

bool myStackEmpty(MyStack* obj) {
    return (obj->rear == 0 && obj->front == 0);
}

void myStackFree(MyStack* obj) {
    obj->rear = 0;
    obj->front = 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值