LeetCode のインタビューの質問 03.04. スタックをチームに変える

記事ディレクトリ

1. タイトル

  2 つのスタックを使用してキューを実装する MyQueue クラスを実装します。

  ここをクリックすると質問にジャンプします

例:

MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 1 を返します
queue.pop(); // 1 を返します
queue.empty(); // falseを返す

例証します:

  • 使用できるのは標準のスタック操作のみです。つまりpush to toppeek/pop from top、 、sizeおよび のis empty操作のみが有効です。
  • 使用している言語はスタックをサポートしていない可能性があります。標準のスタック操作である限り、listor (両端キュー)を使用してスタックをシミュレートできます。deque
  • popすべての操作は有効であると想定されます (たとえば、空のキューはor操作を呼び出しませんpeek)。

2. C# の問題の解決策

  非常に単純な質問ですが、キューに入るときは要素を にプッシュしinStack、デキューするときはinStack要素を順番に押してoutStack先頭の要素をポップアウトします。

public class MyQueue {
    
    
    private Stack<int> inStack, outStack;

    /** Initialize your data structure here. */
    public MyQueue() {
    
    
        inStack = new Stack<int>();
        outStack = new Stack<int>();
    }
    
    /** Push element x to the back of queue. */
    public void Push(int x) {
    
    
        Reverse(outStack, inStack);
        inStack.Push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int Pop() {
    
    
        Reverse(inStack, outStack);
        return outStack.Pop();
    }
    
    /** Get the front element. */
    public int Peek() {
    
    
        Reverse(inStack, outStack);
        return outStack.Peek();
    }
    
    /** Returns whether the queue is empty. */
    public bool Empty() {
    
    
        return (inStack.Count | outStack.Count) == 0;
    }

    // 将 st1 中的元素压入 st2 中
    private void Reverse(Stack<int> st1, Stack<int> st2) {
    
    
        while (st1.Count != 0) st2.Push(st1.Pop());
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.Push(x);
 * int param_2 = obj.Pop();
 * int param_3 = obj.Peek();
 * bool param_4 = obj.Empty();
 */
  • 時間の複雑さ: なし。
  • スペースの複雑さ: なし。

おすすめ

転載: blog.csdn.net/zheliku/article/details/132724669