代码随想录算法训练营第十天| 232. 用栈实现队列、225. 用队列实现栈

232. 用栈实现队列

题目链接:. - 力扣(LeetCode)

解题思路:尾指针指向当前元素的下一个位置;将元素入栈,再出栈进入另一个栈,得到的栈顶元素就是队头元素

C:

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) {
    return obj->stackInTop == 0 && obj->stackOutTop == 0;
}

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

java:stack.peek(返回栈顶元素)

class MyQueue {
    Stack stackIn;
    Stack stackOut;

    public MyQueue() {
        stackIn = new Stack<>();
        stackOut = new Stack<>();
    }
    
    public void push(int x) {
        stackIn.push(x);
    }
    
    public int pop() {    
        dumpstackIn();
        return stackOut.pop();
    }
    
    public int peek() {
        dumpstackIn();
        return stackOut.peek();
    }
    
    public boolean empty() {
        return stackIn.isEmpty() && stackOut.isEmpty();
    }

    private void dumpstackIn(){
        if (!stackOut.isEmpty()) return; 
        while (!stackIn.isEmpty()){
                stackOut.push(stackIn.pop());
        }
    }
}

225. 用队列实现栈

题目链接:. - 力扣(LeetCode)

解题思路:借助辅助队列,入队时,先将新元素加入辅助队列,再其后插入原先队列,以此形成逆序

java:queue.poll(),移除并返回队列的头部元素;queue.offer(x),在队尾插入元素;queue.peek(),获取队列头部元素

class MyStack {
    Queue queue1; 
    Queue queue2; 

    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }
    
    public void push(int x) {
        queue2.offer(x); 
        while (!queue1.isEmpty()){
            queue2.offer(queue1.poll());
        }
        Queue queueTemp;
        queueTemp = queue1;
        queue1 = queue2;
        queue2 = queueTemp;
    }
    
    public int pop() {
        return queue1.poll(); 
    }
    
    public int top() {
        return queue1.peek();
    }
    
    public boolean empty() {
        return queue1.isEmpty();
    }
}

你可能感兴趣的:(算法,java,数据结构)