diff --git "a/lcof/\351\235\242\350\257\225\351\242\23009. \347\224\250\344\270\244\344\270\252\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23009. \347\224\250\344\270\244\344\270\252\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227/README.md" index 318f4499a872b..1adc61378b1bd 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23009. \347\224\250\344\270\244\344\270\252\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23009. \347\224\250\344\270\244\344\270\252\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227/README.md" @@ -29,6 +29,11 @@ ## 解法 +- 两个栈,一个负责输入,一个负责输出 +- 入队的元素放入输入栈当中 +- 当出队时,将输入栈当中的所有元素出栈,放入输出栈当中,让栈底的元素跑到最上面来 +- 只有输出栈中没有元素时才进行倒放,不必每一次出队前都进行进行倒放 + ### **Python3** @@ -65,33 +70,29 @@ class CQueue: ### **Java** ```java +import java.util.Stack; + class CQueue { + private Stack stack_1; + private Stack stack_2; - private Deque s1; - private Deque s2; public CQueue() { - s1 = new ArrayDeque<>(); - s2 = new ArrayDeque<>(); + stack_1 = new Stack<>(); + stack_2 = new Stack<>(); } public void appendTail(int value) { - s1.push(value); - if (s2.isEmpty()) { - move(); - } + stack_1.push(value); } public int deleteHead() { - if (s2.isEmpty()) { - move(); + if (stack_2.empty()) { + while (!stack_1.empty()) { + stack_2.push(stack_1.pop()); + } } - return s2.isEmpty() ? -1 : s2.pop(); - } - private void move() { - while (!s1.isEmpty()) { - s2.push(s1.pop()); - } + return stack_2.empty() ? -1 : stack_2.pop(); } } @@ -107,32 +108,32 @@ class CQueue { ```js var CQueue = function () { - this.data = []; - this.helper = []; + this.data = []; + this.helper = []; }; /** * @param {number} value * @return {void} */ CQueue.prototype.appendTail = function (value) { - this.data.push(value); + this.data.push(value); }; /** * @return {number} */ CQueue.prototype.deleteHead = function () { - if (this.data.length) { - while (this.data.length > 1) { - this.helper.push(this.data.pop()); - } - let res = this.data.pop(); - while (this.helper.length) { - this.data.push(this.helper.pop()); + if (this.data.length) { + while (this.data.length > 1) { + this.helper.push(this.data.pop()); + } + let res = this.data.pop(); + while (this.helper.length) { + this.data.push(this.helper.pop()); + } + return res; + } else { + return -1; } - return res; - } else { - return -1; - } }; ```