一个队列实现栈
最近学习数据结构,所以leetcode上找些题巩固学习。题目比较简单,但是自己写出来也可以更好的理解队列和栈这种数据结构。
思路
一个队列实现栈的思想就是循环往复,就是将出队的元素再加入到队列中,这样才size-1个循环后便可以得到原本最上面的数据。
如图,只需循环size-1次就可将3移至队尾,这样我们就可以将3出栈。
如果我们想只是想看一下栈顶,不想出栈,只要再将3添加到最前面即可。
具体代码如下:
import java.util.LinkedList;
import java.util.Queue;
public class MyStack {
Queue<Integer> queue1;
private int size = 0;
public MyStack() {
queue1 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue1.add(x);
size++;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
if (size == 0) {
System.out.println("stack is empty");
}else {
int ret = 0;
for (int i = 0; i <size-1 ; i++) {
ret = queue1.poll();
queue1.add(ret);
}
}
size--;
return queue1.poll();
}
/** Get the top element. */
public int top() {
if (size == 0) {
System.out.println("stack is empty");
return 0;
}else {
int ret = 0;
for (int i = 0; i <size-1 ; i++) {
ret = queue1.poll();
queue1.add(ret);
}
ret = queue1.poll();
queue1.add(ret);
return ret;
}
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue1.isEmpty();
}
}