preface
Hello everyone, my name is Good. I will tell you about the two most commonly used data structures in the front end and share some algorithm problems with you.
The stack
The characteristics of the stack: advanced after out
You can think of a water glass as a stack. Putting something in the stack is like putting water in the glass. When you want to pour out the water, you have to pour out from the last water in the glass, and the water that went in first must be poured out last. The same is true for stacks. Let me draw a picture to make it clear:
- The first one goes in, the last one comes out. After the advanced
The queue
Features of the queue: first in, first out
Now that you have the basics of stacks, I’m sure it’s not too hard to understand queues. Queues are exactly the opposite of the outgoing order of the stack.
- The first element that goes in, the first element that comes out. First in first out
Algorithm problem
- Use stacks to convert between bases
Here we use binary and decimal as examples: The formula for converting a decimal integer to a two-level system is: mod by two
let num = 10;
let stack = []; // Create a stack
let toBinary = function toBinary(num) {
if (num == 0) return stack.unshift(0);
if (num == 1) return stack.unshift(1);
stack.unshift(num % 2); // Put the remainder on the stack
two(Math.floor(num / 2), mode); // Divide by two and recurse to the next round
return stack.join(' '); // Returns binary characters}}console.log(toBinary(num)); / / '1010'
// Convert decimal to binary using the built-in API
console.log((num).toString(2)); / / '1010'
Copy the code
- Using the queue
N people play the game together, count from 1, count to M automatically eliminated; The last person left will win. Which one is left?
let queue = []; // Create a queue
let game = function game(n, m) {
// Put everyone in the queue
for (let i = 1; i <= n; i++) queue.push(i);
// Loop out people
for (let i = 1; count <= m; i++) {
if (queue.length === 1) return queue[0]; // The last person left to return
let move = queue.shift();
if(i ! == m) { queue.push(move); }else {
count = 0; }}}console.log(game(3.2)); / / = > 3
Copy the code