LeetCode 225. 用队列实现栈(打卡第一天)

LeetCode 225.用队列实现栈

题目:

  1. 用队列实现栈
    使用队列实现栈的下列操作:

push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
注意:

你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

解题思路

java
用单个队列实现栈的操作;
由于栈的特性是后进先出,而队列的特点是先进先出,
所以我们需要实现让元素在进队后能处于队顶
实现思路是:
先判断队列是否为空,如果是空队列,直接进队即可;
若不是空队列,可以先求出现有队列长度,用于后续将前边元素逐个出栈再入栈
接着元素进队,
根据之前求得的长度将原队列中的元素排在新元素后,从而实现为“栈”
在这里插入图片描述
实现代码:

class MyStack {

    public LinkedList<Integer> queue=new LinkedList<>();
	/** Initialize your data structure here. */
    /*public MyStack {
    	LinkedList<Integer> queue=new LinkedList<>();
    }*/
    
    /** Push element x onto stack. */
    public void push(int x) {
    	//
    	if(queue.isEmpty())//空队列直接加
    		queue.add(x);
    	else {
    		//非空要将前边元素以此出队往后排
    		int l=queue.size();
    		queue.add(x);
    		for(int i=0;i<l;++i) {
    			queue.add(queue.remove());
    		}
    	}
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
    	return queue.remove();
    }
    
    /** Get the top element. */
    public int top() {
    	return queue.peekFirst();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
    	return queue.isEmpty();
    }
}

/**
 * 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();
 */

开始LeetCode连续两月打卡挑战,第一天!!

发布了11 篇原创文章 · 获赞 6 · 访问量 1611

猜你喜欢

转载自blog.csdn.net/qq_41119146/article/details/104590838