2スタックを持つキューの実装
6759 ワード
始まり
私はあなたの語彙に精通していると仮定している
スタック
キュー
前提条件:あなたはこれを知っている必要があります
Javaの ArrayListに「追加」すると、最後に追加されます. 同様に、JavaScriptを使用する場合、配列に“push”すると、配列の最後に値が追加されます. それで、私は2つのスタック(LIFO)で単純な待ち行列(FIFO)を実装することのこの単純で興味深い話題に遭遇しました
大学でこのプログラムを行ったこと(私はC +でのスクラッチの実装を使用しています)、私は今、より多くの簡潔さがインタビュー準備のために必要であると信じています.
そして、我々の待ち行列は、ここにあります
あなたが理論的な概観が好きであるならば、ここではスーパーニースです
エンド.
私はあなたの語彙に精通していると仮定している
スタック
PUSH = Add to end
POP = Get from end
キュー
ENQUEUE = Add to end
DEQUEUE = Return from beginning
Javaの
大学でこのプログラムを行ったこと(私はC +でのスクラッチの実装を使用しています)、私は今、より多くの簡潔さがインタビュー準備のために必要であると信じています.
import java.util.ArrayList;
import java.util.List;
public class MyStack {
private final List<Integer> stack = new ArrayList<>();
void push(int item) {
stack.add(item);
}
int pop() {
if (!stack.isEmpty()) {
return stack.remove(stack.size() - 1);
}
return -1; // if nothing found
}
int size() {
return stack.size();
}
boolean isEmpty() {
return stack.isEmpty();
}
}
だから、今私たちのスタックを持って-それは簡単ですそして、我々の待ち行列は、ここにあります
public class MyQueueWithTwoStacks {
private final MyStack firstStack;
private final MyStack secondStack;
public MyQueueWithTwoStacks() {
this.firstStack = new MyStack();
this.secondStack = new MyStack();
}
boolean isEmpty() {
return firstStack.isEmpty() && secondStack.isEmpty();
}
int size() {
return firstStack.size() + secondStack.size();
}
void enqueue(int item) {
firstStack.push(item);
}
/**
* We will use the second stack to out the values, if the second bucket is
* empty that means we need to copy over all stack1 entries to it
*
* @return returns the value
*/
int dequeue() {
if (secondStack.isEmpty()) {
while (!firstStack.isEmpty()) {
secondStack.push(firstStack.pop());
}
}
return secondStack.pop();
}
}
参照:Reference
この問題について(2スタックを持つキューの実装), 我々は、より多くの情報をここで見つけました https://dev.to/saurabhpro/implementing-queue-with-2-stacks-3l9fテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol