How to implement Queue in Javascript?

The main principle of queue datastructure is FIFO (First in First Out). If we compare with real life queue example, people standing in a queue are nodes. Queue implementation can be done in two ways: using array and using object.

Implement Queue using array:

First we create an array named queue.

Second we push some elements using push()

Third we remove elements using shift()

Fourth to check if the queue is empty we use queue.length and see whether empty or not

// Initializing queue array.
var queue = [];

// Inserting vales into the queue.
queue.push(1);
queue.push(2);
queue.push(3);
queue.push(4);
queue.push(5);

console.log("The current queue is: ", queue);

// Removing element form queue using array method: shift()
var removed_element = queue.shift();
console.log("Removed element is: ", removed_element);

console.log("The current queue is: ", queue);

// We can check the if the queue is empty or not using the array.length method.
if (queue.length > 0) {
  console.log("The Queue is not empty!");
} else {
  console.log("The Queue is empty!");
}
Output:
queue using arrays

Using objects:

Here we will create a class node.

class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}
This class has 2 parameters:
  • this.value – the value which node stores
  • this.next – the pointer to next node in queue and initially it is assigned to null as there is no nodes in queue

Now we need to create another class to store all the nodes and perform queue operations.

class Queue {
    constructor() {
        this.head = null;
        this.tail = null;
        this.length = 0;
    }
}
This class has 3 properties:
  • this.head – pointer to first node
  • this.tail -pointer to last node
  • this.length – number of nodes in queue
Methods of a queue:
  • enqueue() – To add elements at rear end of the queue
  • dequeue() – To remove elements from front end of the queue
  • peek() – To get the front element without removing it.
  • isEmpty() – To check whether an element is present in the queue or not.
  • print()  – To print the elements in the queue
  • getLength() – Returns the number of nodes in a queue.
class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

class Queue {
    constructor() {
        this.head = null;
        this.tail = null;
        this.length = 0;
    }

    enqueue(value) {
        const node = new Node(value);

        if (this.head) {
            this.tail.next = node;
            this.tail = node;
        } else {
            this.head = node;
            this.tail = node
        }

        this.length++;
    }

    dequeue() {
        const current = this.head;
        this.head = this.head.next;
        this.length--;

        return current.value;
    }

    isEmpty() {
        return this.length === 0;
    }

    peek() {
        return this.head.value;
    }

    getLength() {
        return this.length;
    }

    print() {
        let current = this.head;

        while(current) {
            console.log(current.value);
            current = current.next;
        }
    }
}

const queue = new Queue();
console.log('is empty?', queue.isEmpty())
queue.enqueue(12)
queue.enqueue(24)
queue.enqueue(36)
queue.enqueue(48)
queue.enqueue(60)
console.log('Queue:')
queue.print()
console.log('Remove 2 elements')
queue.dequeue()
queue.dequeue()
console.log('Queue:');  queue.print()
console.log('is empty?', queue.isEmpty())
console.log('Length',    queue.getLength())
console.log('Head', queue.peek())
Output:

To know more about the data structures in javascript click here!

7 Data Structures in JavaScript you need to know.

In this article, let’s try to understand the important data structures in javascript.

What is a Data Structure?

Data Structure is a storage that is used to store and organize data. It is a way of storing and organizing the data in such a way that it can be accessed more efficiently. It refers to group of data values, the relationship between them and the operations that can be performed on it. JavaScript has dynamic arrays i.e their size and type are not determined.

Now let us jump into the data structures in javascript.

1.Array Data Structure

Most popular linear data structure. All the elements are of same data type and stored in contiguous memory location. An array is represented by set of elements with index.

2.Stack Data Structure

Stack works on Last in First out(LIFO) principle. It is a linear data structure. It contains only one pointer and that points to the top element or last added element of the stack. Whenever we add or delete an element it is added or deleted from the top. Like a pile of books.

3.Queue Data Structure

Queue works on the principle of First in First out(FIFO). It is a linear data structure. It contains two-pointers front pointer and rear pointer. The front pointer contains address of the starting element and rear pointer contains address of the last element. The two main methods used for implementation. Enqueue is process of adding an element in the queue and dequeue is process of removing an element from the queue.

4.Linked List

Linked list is a linear data structure and here unlike arrays elements are stored in non-contiguous memory locations. It is made of group of nodes. Each node has its own data and address to the next node.

Here in linked list you have to start from head and work through the way to desired element. First element is head and last element is tail.

  • List don’t have indexes, so we cannot access elements randomly.
  • Insertion and deletion is more efficient we have to just redirect the pointers.

5.Trees

Tree is a non-linear data structure which consists of nodes connected by edges. This data structure link nodes via parent/child relationship. The top node is called root node and all the other nodes come off that node are called children. The nodes at the bottom of the tree are called leaf nodes. The height of the tree is determined by number of parent/child relationships it has.

Points to note:
  • A connection is valid between nodes when it is from parent to child.
  • Connection between siblings or child to parent are not valid.
  • Tree must have only one root node.
Examples:
  • File folders in our operating system
  • DOM model
Popular Tree based data structure
  • Binary Tree
  • Binary Search Tree
  • AVL Tree
  • Red-Black Tree
  • N-ary Tree
  • 2-3 Tree

6.Graph Data Structure

Graphs are relation based data structure helpful in storing web-like or network relationships. It is made up of a finite collection of nodes called vertices, and the connections between them are known as edges. Graphs can be of two types: Directed graph and undirected graph.

Often used in Social networks, geolocalization(Google maps) and Web analytics.

7.Hash table

Hash table is also known as hash map or hash. Generally used in Object data structures, map or dictionary as it queries through a key and hash function. Hashing is a technique of mapping keys, values into the hash table using a hash function. Key is a searched string and value is the data paired with the key. Insertion and search function are very fast irrespective of the size of the table. Hash tables are built using arrays. In real life example of hash table is in schools each student is assigned a unique id number.

4 Data Structures one must know in Python

In Python we have 4 built-in data structures which covers 80% of the real-world data structures. These are classified as non-primitive data structures because they store a collection of values in various format than a single value. Some can store data structures within data structures, creating depth and complexity.

Built-in data structures are predefined data structures that come along with Python. Lists and tuples are ordered sequence of objects. Unlike strings that contain only characters, lists and tuples can contain any type of objects.

  • List and tuples are like arrays.
  • Tuples like strings are immutables.
  • Lists are mutables so they can be converted after their creation.
  • Sets are mutable unordered sequence of unique elements whereas frozensets are immutable sets

Lists are enclosed in brackets: l =[1,2,’a’]

Tuples are enclosed in parentheses: t=(1,2,’a’)

Dictionaries are built with curly brackets: d= {‘a’:1, ‘b’:2}

Set are built with curly brackets: s= {1,2,3}

Tuples are faster and consume less memory.

Lists:

            They are used to store data of different data types in a sequential manner. It stores heterogeneous data in sequential order. There are two types of indexing: positive index(most common method) and negative index.

Indexing:

Positive Index means every element has an index that starts from 0 and goes until last element.

Negative Index starts from -1 and it starts retrieving from last element.

Slicing:

In Python List slicing is the most common practice to solve problems efficiently. If we want to use a range of elements from the list we can access those range with slicing and the operator used is colon (:)

Syntax:

List [start:end:index jump]

Type error occurs when data types other than integer are used to access like in our example float is used. Index error occurs when we try to access indexes out of range.

List Functions:

Let us see some functions in the sample code snippet:

Tuple:

            Tuples are same as list but the only exception is that data cannot be changed once entered into the tuple. They are immutable. Since it is immutable the length is fixed, to grow or shrink a tuple we need to create a new tuple. Like list tuple also has some methods

Dictionaries:           

Dictionary is a datastructure which stores the data in the form of key:value pairs. Dictionary is a collection of ordered, changeable and does not allow duplication. Key-value is provided in dictionary to make it more optimized. For better understanding, dictionary can be compared to a telephone directory with tens of thousands of names and phone numbers. Here the constant values are names and phone numbers these are the keys and the various names and phone numbers fed to the keys are called values.

Sets:

            Sets are a collection of unordered elements that are unique. Even if the data is repeated more than once it will be entered in the set only once. It is same as arithmetic sets.

Sets are created same way as in dictionary by using curly brackets but instead of key value pairs we pass values directly.

Now let us see a sample code snippet with set creation and its operations such as union, intersection, difference, symmetric_difference

  • Union combines both sets
  • Intersection finds the elements present in both sets
  • Difference deletes the elements present in both sets and outputs the elements present only in the set
  • Symmetric_difference is same as difference but outputs the data which is remaining in both sets.

These are all the four basic data structures one need to know while learning python programming.