From 4b762c3060993df94f6d62e6e2c1e15fad5593b7 Mon Sep 17 00:00:00 2001 From: yuanguangxin <274841922@qq.com> Date: Thu, 2 Jul 2020 18:16:52 +0800 Subject: [PATCH] update --- .../q232_用栈实现队列/f1/MyQueue.java | 51 +++++++++++++++++++ .../q232_用栈实现队列/f2/MyQueue.java | 49 ++++++++++++++++++ 2 files changed, 100 insertions(+) create mode 100644 src/栈相关/q232_用栈实现队列/f1/MyQueue.java create mode 100644 src/栈相关/q232_用栈实现队列/f2/MyQueue.java diff --git a/src/栈相关/q232_用栈实现队列/f1/MyQueue.java b/src/栈相关/q232_用栈实现队列/f1/MyQueue.java new file mode 100644 index 0000000..9a6f4cf --- /dev/null +++ b/src/栈相关/q232_用栈实现队列/f1/MyQueue.java @@ -0,0 +1,51 @@ +package 栈相关.q232_用栈实现队列.f1; + +import java.util.Stack; + +/** + * 双栈 入队o(n) 出队o(1) + */ +class MyQueue { + + private Stack s1 = new Stack<>(); + private Stack s2 = new Stack<>(); + private Integer front; + + /** Initialize your data structure here. */ + public MyQueue() { + + } + + /** Push element x to the back of queue. */ + public void push(int x) { + if (s1.empty()){ + front = x; + } + while (!s1.isEmpty()){ + s2.push(s1.pop()); + } + s2.push(x); + while (!s2.isEmpty()){ + s1.push(s2.pop()); + } + } + + /** Removes the element from in front of queue and returns that element. */ + public int pop() { + int value = s1.pop(); + if (!s1.empty()){ + front = s1.peek(); + } + return value; + } + + /** Get the front element. */ + public int peek() { + return front; + } + + /** Returns whether the queue is empty. */ + public boolean empty() { + return s1.isEmpty(); + } +} diff --git a/src/栈相关/q232_用栈实现队列/f2/MyQueue.java b/src/栈相关/q232_用栈实现队列/f2/MyQueue.java new file mode 100644 index 0000000..22a6e97 --- /dev/null +++ b/src/栈相关/q232_用栈实现队列/f2/MyQueue.java @@ -0,0 +1,49 @@ +package 栈相关.q232_用栈实现队列.f2; + +import java.util.Stack; + +/** + * 双栈 入队o(1) 出队平均o(1),最坏o(n) + */ +class MyQueue { + + private Stack s1 = new Stack<>(); + private Stack s2 = new Stack<>(); + private Integer front; + + /** Initialize your data structure here. */ + public MyQueue() { + + } + + /** Push element x to the back of queue. */ + public void push(int x) { + if (s1.empty()){ + front = x; + } + s1.push(x); + } + + /** Removes the element from in front of queue and returns that element. */ + public int pop() { + if (s2.isEmpty()) { + while (!s1.isEmpty()){ + s2.push(s1.pop()); + } + } + return s2.pop(); + } + + /** Get the front element. */ + public int peek() { + if (!s2.isEmpty()) { + return s2.peek(); + } + return front; + } + + /** Returns whether the queue is empty. */ + public boolean empty() { + return s1.isEmpty() && s2.isEmpty(); + } +}