Skip to content

Commit

Permalink
Improved task 225
Browse files Browse the repository at this point in the history
  • Loading branch information
javadev authored Aug 17, 2024
1 parent 5943a79 commit 80d7849
Showing 1 changed file with 22 additions and 45 deletions.
Original file line number Diff line number Diff line change
@@ -1,66 +1,43 @@
package g0201_0300.s0225_implement_stack_using_queues

// #Easy #Stack #Design #Queue #2022_10_26_Time_248_ms_(73.44%)_Space_36.1_MB_(43.75%)
// #Easy #Stack #Design #Queue #2024_08_17_Time_147_ms_(88.57%)_Space_35.9_MB_(87.62%)

import java.util.LinkedList
import java.util.Queue

class MyStack {
private var queuePair = Pair(LinkedList<Int>(), LinkedList<Int>())
private var top: Int? = null
class MyStack() {
private val queue1: Queue<Int> = LinkedList()
private val queue2: Queue<Int> = LinkedList()

fun push(x: Int) {
queuePair.first.addLast(x)
top = x
queue1.add(x)
}

fun pop(): Int {
if (isQueuesEmpty()) {
throw Exception()
while (queue1.size > 1) {
queue2.add(queue1.remove())
}
val queuePair = selectSourceAndDestinationQueues(queuePair)
var value = 0
repeat(queuePair.first.size) {
when (queuePair.first.size) {
2 -> {
top = queuePair.first.removeFirst()
queuePair.second.addLast(top)
}
1 -> {
value = queuePair.first.removeFirst()
}
else -> {
queuePair.second.addLast(queuePair.first.removeFirst())
}
}
}
return value
val top = queue1.remove()
queue1.clear()
queue1.addAll(queue2)
queue2.clear()
return top
}

fun top(): Int {
if (isQueuesEmpty()) {
throw Exception()
while (queue1.size > 1) {
queue2.add(queue1.remove())
}
return top!!
val top = queue1.remove()
queue2.add(top)
queue1.clear()
queue1.addAll(queue2)
queue2.clear()
return top
}

fun empty(): Boolean {
return isQueuesEmpty()
}

private fun isQueuesEmpty(): Boolean {
if (queuePair.first.isEmpty() && queuePair.second.isEmpty()) {
return true
}
return false
}

private fun selectSourceAndDestinationQueues(queuePair: Pair<LinkedList<Int>, LinkedList<Int>>):
Pair<LinkedList<Int>, LinkedList<Int>> {
return if (queuePair.first.isNotEmpty()) {
Pair(queuePair.first, queuePair.second)
} else {
Pair(queuePair.second, queuePair.first)
}
return queue1.isEmpty()
}
}

Expand Down

0 comments on commit 80d7849

Please sign in to comment.