Home Java Javascript - Stack and queues

Javascript - Stack and queues

java20230615174904.jpg

In programming data structures like stacks and queues,allows you to order items waiting to be processed.

We will see that implement these data structures under Javascript using pre-existing methods.

The Array

The JavaScript arrays. The most common example is:

var myArray = new Array(1, 2, 3, 4, 5) ;

Imagine that Javascript Stack and queues are nothing but the tables for which four methods can be used:

pop()

push()

shift()

unshift().

The stack: the FILO structure

FILO is an acronym meaning "First In Last Out". Here we will use the following methods:

push(): adds an element to the end of the array, thus increasing its size by one.

pop(): which removes the last element of the array, thereby reducing the size by 1.

Example a stack:

myArray.push(6); // add a 6th element myArray.pop(); // we remove it myArray.pop(); // we remove the 6th element myArray.push(myArray.pop()); // no effect ! /* The resulting array is [1|2|3|4] */

Queue: FIFO structure

FIFO is an acronym meaning "First In First Out". Here we will use the following methods:

push() adds an element to the end of the array.

shift() removes the first element of the array, thereby reducing the size by one, while shifting the elements to the left.

myArray.push(6); // add the the 6th element myArray.shift(); // We remove the 1 myArray.shift(); // We remove the 2 myArray.push(myArray.shift()); // Put the first element at the last position! /* The resulting array is [4|5|6|3] */

  • Java

LEAVE A REPLY

Please enter your comment!
Please enter your name!