长大后想做什么?做回小孩!

0%

LeetCode——用队列实现栈

NO.225 用队列实现栈 简单

3g45b4.png

思路一:使用队列API 其实没有太搞明白这个题目的意思。。。leetcode打卡活动第一天题目。

主要是push()方法每次将新加入元素x之前的元素都按序出队并重新入队,这样新元素x就在队头。

然后pop()、top()、empty()直接调用队列API就好。。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class MyStack {

Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
this.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();
}

/** Get the top element. */
public int top() {
return queue.peek();
}

/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}

时间复杂度:push()是O(n),其余三个方法时O(1)


本人菜鸟,有错误请告知,感激不尽!

更多题解和学习记录博客:博客github