您的位置:首页 > 产品设计 > UI/UE

Implement Stack using Queues

2016-06-10 01:55 267 查看
这道题可以用一个queue来实现,但在push方法中创建一个临时的queue,来实现倒置已有元素,这个思路很好。

参考:点击打开链接

class MyStack {
Queue<Integer> queue = new LinkedList<>();
// Push element x onto stack.
public void push(int x) {
Queue<Integer> temp = new LinkedList<>();
while (queue.size() > 0) {
temp.offer(queue.peek());
queue.poll();
}
queue.offer(x);
while (temp.size() > 0) {
queue.offer(temp.peek());
temp.poll();
}
}

// Removes the element on top of the stack.
public void pop() {
queue.poll();
}

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

// Return whether the stack is empty.
public boolean empty() {
return queue.isEmpty();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: