-
Notifications
You must be signed in to change notification settings - Fork 13
/
MyQueue.java
59 lines (52 loc) · 1.33 KB
/
MyQueue.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.lintcode;
import java.util.Stack;
/**
* lintCode 44 用栈实现队列
*
* Created by gegf on 2018/2/11.
*/
public class MyQueue {
public Stack<Integer> stackPush;
public Stack<Integer> stackPop;
public MyQueue() {
// do intialization if necessary
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
/*
* @param element: An integer
* @return: nothing
*/
public void push(int element) {
// write your code here
stackPush.push(element);
}
/*
* @return: An integer
*/
public int pop() {
// write your code here
if(stackPop.isEmpty() && stackPush.isEmpty()){
throw new RuntimeException("QUEUE IS EMPTY");
}else if(stackPop.isEmpty()){
while (!stackPush.isEmpty()){
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
/*
* @return: An integer
*/
public int top() {
// write your code here
if(stackPop.isEmpty() && stackPush.isEmpty()){
throw new RuntimeException("QUEUE IS EMPTY");
}else if(stackPop.isEmpty()){
while (!stackPush.isEmpty()){
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
}