Queue类和Deque类请参考:Queue 和 Deque
循环队列——击鼓传花游戏(队列)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| function hotPotato(elementsList, num) { const queue = new Queue(); const elimitatedList = []; for (let i = 0; i < elementsList.length; i++) { queue.enqueue(elementsList[i]); } while (queue.size() > 1) { for (let i = 0; i < num; i++) { queue.enqueue(queue.dequeue()); } elimitatedList.push(queue.dequeue()); } return { eliminated: elimitatedList, winner: queue.dequeue() }; }
const names = ['John', 'Jack', 'Jenny', 'Kate', 'Tom']; const res = hotPotato(names, 7);
res.eliminated.forEach(ele => { console.log(`${ele} 在击鼓传花游戏中被淘汰!`) })
console.log(`胜利者是${res.winner}!`)
|
回文检查器(双端队列)
一般回文检查我们使用双指针的方式,但是使用双端队列也是一种好办法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| function palindromeChecker(aString) { if (aString === undefined || aString === null || !aString.length) return false; const deque = new Deque(); const lowerString = [...aString]; let firstChar, lastChar; for (let i = 0; i < lowerString.length; i++) { deque.addBack(lowerString[i]); } while (deque.size() > 1) { firstChar = deque.removeFront(); lastChar = deque.removeBack(); if (firstChar !== lastChar) { return false; } else { continue; }; }; return true; }
const aString1 = 'helloaolleh'; const aString2 = 'helloworldolleh';
console.log(palindromeChecker(aString1)); console.log(palindromeChecker(aString2));
|