Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4b762c3

Browse files
update
1 parent d6d62cd commit 4b762c3

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package 栈相关.q232_用栈实现队列.f1;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
* 双栈 入队o(n) 出队o(1)
7+
*/
8+
class MyQueue {
9+
10+
private Stack<Integer> s1 = new Stack<>();
11+
private Stack<Integer> s2 = new Stack<>();
12+
private Integer front;
13+
14+
/** Initialize your data structure here. */
15+
public MyQueue() {
16+
17+
}
18+
19+
/** Push element x to the back of queue. */
20+
public void push(int x) {
21+
if (s1.empty()){
22+
front = x;
23+
}
24+
while (!s1.isEmpty()){
25+
s2.push(s1.pop());
26+
}
27+
s2.push(x);
28+
while (!s2.isEmpty()){
29+
s1.push(s2.pop());
30+
}
31+
}
32+
33+
/** Removes the element from in front of queue and returns that element. */
34+
public int pop() {
35+
int value = s1.pop();
36+
if (!s1.empty()){
37+
front = s1.peek();
38+
}
39+
return value;
40+
}
41+
42+
/** Get the front element. */
43+
public int peek() {
44+
return front;
45+
}
46+
47+
/** Returns whether the queue is empty. */
48+
public boolean empty() {
49+
return s1.isEmpty();
50+
}
51+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package 栈相关.q232_用栈实现队列.f2;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
* 双栈 入队o(1) 出队平均o(1),最坏o(n)
7+
*/
8+
class MyQueue {
9+
10+
private Stack<Integer> s1 = new Stack<>();
11+
private Stack<Integer> s2 = new Stack<>();
12+
private Integer front;
13+
14+
/** Initialize your data structure here. */
15+
public MyQueue() {
16+
17+
}
18+
19+
/** Push element x to the back of queue. */
20+
public void push(int x) {
21+
if (s1.empty()){
22+
front = x;
23+
}
24+
s1.push(x);
25+
}
26+
27+
/** Removes the element from in front of queue and returns that element. */
28+
public int pop() {
29+
if (s2.isEmpty()) {
30+
while (!s1.isEmpty()){
31+
s2.push(s1.pop());
32+
}
33+
}
34+
return s2.pop();
35+
}
36+
37+
/** Get the front element. */
38+
public int peek() {
39+
if (!s2.isEmpty()) {
40+
return s2.peek();
41+
}
42+
return front;
43+
}
44+
45+
/** Returns whether the queue is empty. */
46+
public boolean empty() {
47+
return s1.isEmpty() && s2.isEmpty();
48+
}
49+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /