-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEasy_225_ImpStackUseQueue.kt
More file actions
55 lines (45 loc) · 1.19 KB
/
Easy_225_ImpStackUseQueue.kt
File metadata and controls
55 lines (45 loc) · 1.19 KB
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
package com.boycoder.problems.stack
import java.util.*
/**
* @Author: zhutao
* @datetime: 2021/6/22
* @desc:
*/
object Easy_225_ImpStackUseQueue {
/** Initialize your data structure here. */
val queue = LinkedList<Int>()
val backup = LinkedList<Int>()
/** Push element x onto stack. */
fun push(x: Int) {
queue.addLast(x)
}
/** Removes the element on top of the stack and returns that element. */
fun pop(): Int {
return popByType(true)
}
private fun popByType(isOut: Boolean): Int {
var value = 0
while (!queue.isEmpty()) {
if (queue.size == 1) {
value = queue.removeFirst()
if (!isOut) {
backup.addLast(value)
}
} else {
backup.addLast(queue.removeFirst())
}
}
while (!backup.isEmpty()) {
queue.addLast(backup.removeFirst())
}
return value
}
/** Get the top element. */
fun top(): Int {
return popByType(false)
}
/** Returns whether the stack is empty. */
fun empty(): Boolean {
return queue.isEmpty() && backup.isEmpty()
}
}