gpt4 book ai didi

javascript - 使用2个栈实现队列

转载 作者:行者123 更新时间:2023-11-27 22:54:51 25 4
gpt4 key购买 nike

谁能告诉我。如何使用2个堆栈实现队列。具体来说,实现入队和出队方法。

如果你们告诉我 php 或 JavaScript 编程将会很有帮助

最佳答案

这是一个个人示例,我确信它可以进一步优化,但它允许在 JS 中实现队列出列和查看功能。

function processData(input) {
let stackOne = [];
let stackTwo = [];
let parsableInput = input.split('\n');

for(let i = 1; i < parsableInput.length; i++) {
// handle 1 push
if (parsableInput[i][0] === '1') {
enqueue(stackOne, stackTwo, parsableInput[i].slice(2));
}
// handle 2
if (parsableInput[i] === '2') {
dequeue(stackTwo);
}
// handle 3
if (parsableInput[i] === '3') {
console.log(peek(stackTwo));
}
}
}

function enqueue(stackOne, stackTwo, queuedValue) {
while(stackTwo.length !== 0) {
stackOne.push(stackTwo.pop());
}

stackOne.push(queuedValue);

while(stackOne.length !== 0) {
stackTwo.push(stackOne.pop());
}
}

function dequeue(stackTwo) {
return stackTwo.pop();
}

function peek(stackTwo) {

let stringToBeParsed = stackTwo[stackTwo.length - 1];
let parsedString = stringToBeParsed.slice(0, stringToBeParsed.length);

if (parsedString) {
return parsedString;
} else {
console.log('Error: there is nothing to peek at!');
}
}

关于javascript - 使用2个栈实现队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37716113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com