コーディングテスト練習-Implement Stack使用キュー


理解する


スタックの内部関数実装の問題.ただし、実装時にはキューで使用される関数のみを使用する必要があります.

02.計画


トップ,emptyは基本的に実現すればよい.Qのpollを使用してpopを実現するには、pushからデータを逆方向に入れる必要がある場合があります.

03.実行

class MyStack() {

    /** Initialize your data structure here. */
    private var queue = LinkedList<Int>()


    /** Push element x onto stack. */
    fun push(x: Int) {
        if (queue.isEmpty()){
            queue.offer(x)
        } else {
            val tempQueue = LinkedList<Int>()
            tempQueue.offer(x)
            while (queue.isNotEmpty()) {
                tempQueue.offer(queue.poll())
            }
            queue = tempQueue
        }
    }

    /** Removes the element on top of the stack and returns that element. */
    fun pop(): Int {
        return queue.poll()!!
    }

    /** Get the top element. */
    fun top(): Int {
        return queue.peek()!!
    }

    /** Returns whether the stack is empty. */
    fun empty(): Boolean {
        return queue.isEmpty()
    }

}

class MyStack2() {

    /** Initialize your data structure here. */
    private var queue = LinkedList<Int>()


    /** Push element x onto stack. */
    fun push(x: Int) {
        if (queue.isEmpty()){
            queue.offer(x)
        } else {
            val preQueueSize = queue.size
            queue.offer(x)
            for (i in 0 until preQueueSize) {
                queue.offer(queue.poll())
            }
        }
    }

    /** Removes the element on top of the stack and returns that element. */
    fun pop(): Int {
        return queue.poll()!!
    }

    /** Get the top element. */
    fun top(): Int {
        return queue.peek()!!
    }

    /** Returns whether the stack is empty. */
    fun empty(): Boolean {
        return queue.isEmpty()
    }

}

レビュー


製品があることを発見する過程でqueueを使用することはなかった(使用する必要があるが使用していない場合があるかもしれない...)queueで使用される関数(peek、offer、poll)の名前は見慣れない.
コミット結果の速度は正確で、メモリの使用量が悪い.
Runtime: 148 ms, faster than 80.00% of Kotlin online submissions for Implement Stack using Queues.
Memory Usage: 34.9 MB, less than 5.00% of Kotlin online submissions for Implement Stack using Queues.