Skip to content

Commit 5b1c09d

Browse files
LeetCode第232题:栈实现队列
1 parent 971745a commit 5b1c09d

File tree

2 files changed

+159
-39
lines changed

2 files changed

+159
-39
lines changed

.idea/workspace.xml

Lines changed: 64 additions & 39 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
package leetcode.stack;
2+
3+
import java.util.LinkedList;
4+
import java.util.List;
5+
6+
/**
7+
* <p>
8+
* LeetCode第232题:栈实现队列
9+
* 使用栈实现队列的下列操作:
10+
11+
push(x) -- 将一个元素放入队列的尾部。
12+
pop() -- 从队列首部移除元素。
13+
peek() -- 返回队列首部的元素。
14+
empty() -- 返回队列是否为空。
15+
示例:
16+
17+
MyQueue queue = new MyQueue();
18+
19+
queue.push(1);
20+
queue.push(2);
21+
queue.peek(); // 返回 1
22+
queue.pop(); // 返回 1
23+
queue.empty(); // 返回 false
24+
说明:
25+
26+
你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
27+
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
28+
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
29+
* </p>
30+
*
31+
* @author jwzhao
32+
* @version 1.0
33+
* @date 2019/1/28 10:56
34+
*/
35+
public class StackForQueue {
36+
37+
/**
38+
* 实现栈的底层list
39+
*/
40+
private List<Integer> stack1;
41+
42+
private List<Integer> stack2;
43+
44+
/** Initialize your data structure here. */
45+
public StackForQueue() {
46+
stack1 = new LinkedList<>();
47+
stack2 = new LinkedList<>();
48+
}
49+
50+
/** Push element x to the back of queue. */
51+
public void push(int x) {
52+
if (this.empty()){
53+
stack1.add(x);
54+
}else{
55+
stack2.add(x);
56+
stack2.addAll(stack1);
57+
stack1 = stack2;
58+
// 清空stack2
59+
stack2 = new LinkedList<>();
60+
}
61+
}
62+
63+
/** Removes the element from in front of queue and returns that element. */
64+
public int pop() {
65+
int pop = stack1.get(stack1.size()-1);
66+
stack1.remove(stack1.size()-1);
67+
return pop;
68+
}
69+
70+
/** Get the front element. */
71+
public int peek() {
72+
return stack1.get(stack1.size()-1);
73+
}
74+
75+
/** Returns whether the queue is empty. */
76+
public boolean empty() {
77+
return stack1.size() == 0;
78+
}
79+
80+
public static void main(String[] args) {
81+
StackForQueue stackForQueue = new StackForQueue();
82+
stackForQueue.push(1);
83+
stackForQueue.push(2);
84+
stackForQueue.push(3);
85+
System.out.println(stackForQueue.stack1);
86+
System.out.println(stackForQueue.peek());
87+
System.out.println(stackForQueue.pop());
88+
System.out.println(stackForQueue.empty());
89+
System.out.println(stackForQueue.peek());
90+
System.out.println(stackForQueue.pop());
91+
System.out.println(stackForQueue.peek());
92+
System.out.println(stackForQueue.pop());
93+
System.out.println(stackForQueue.empty());
94+
}
95+
}

0 commit comments

Comments
 (0)