·255.用队列实现栈

题解思路 ❤

完全忘了java有自带的函数了
而且完全忽略了题目要求的是队列功能实现栈。

  • 用一个队列即可
    在这里插入图片描述

JAVA代码

class MyStack {
    Queue<Integer> queue;
    /** Initialize your data structure here. */
    public MyStack() {
        queue= new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queue.add(x);
        for(int i=1 ; i<queue.size() ; i++)
            queue.add(queue.remove());
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue.poll(); //和pop功能相似
    }
    
    /** Get the top element. */
    public int top() {
        return queue.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.size() == 0 ;
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

C代码

typedef struct {
    int top;
    int stack[100000];
} MyStack;

/** Initialize your data structure here. */

MyStack* myStackCreate() {
    MyStack *s; // 记得新建结构体
    s = (MyStack *)malloc(sizeof(MyStack));
    s->top = -1;
    return s;
}

/** Push element x onto stack. */
void myStackPush(MyStack* obj, int x) {
    obj->stack[++obj->top]=x; //是->不是.
}

/** Removes the element on top of the stack and returns that element. */
int myStackPop(MyStack* obj) {
    return obj->stack[obj->top--];
}

/** Get the top element. */
int myStackTop(MyStack* obj) {
    return obj->stack[obj->top];
}

/** Returns whether the stack is empty. */
bool myStackEmpty(MyStack* obj) {
    return obj->top==-1 ? 1 : 0;
}

void myStackFree(MyStack* obj) {
    obj->top=-1;
    free(obj); // 有一个free
}

/**
 * Your MyStack struct will be instantiated and called as such:
 * MyStack* obj = myStackCreate();
 * myStackPush(obj, x);
 
 * int param_2 = myStackPop(obj);
 
 * int param_3 = myStackTop(obj);
 
 * bool param_4 = myStackEmpty(obj);
 
 * myStackFree(obj);
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值