How to create and use stacks and queues

Stacks and queues are two basic data structures that can be used to store data in a specific order. Stacks follow the LIFO (last-in, first-out) principle, while queues follow the FIFO (first-in, first-out) principle.

Stacks

Stacks are like a pile of plates. You can only add plates to the top of the pile, and you can only remove plates from the top of the pile.

Here is how you can create a stack in JavaScript:

var stack = [];

To add an element to the stack, you use the push() method:

stack.push("Hello");

To remove an element from the stack, you use the pop() method:

var topElement = stack.pop();

Queues

Queues are like a line of people waiting to buy tickets. You can only add people to the back of the line, and you can only remove people from the front of the line.

Here is how you can create a queue in JavaScript:

var queue = [];

To add an element to the queue, you use the push() method:

queue.push(1);

To remove an element from the queue, you use the shift() method:

var firstElement = queue.shift();