Implementing a deque (double-ended queue) data structure in JavaScript can be achieved by using an array to simulate a data structure that supports insertion and deletion at both ends. Here's how to implement the basic functionality of a deque in JavaScript:
Defining the Deque Class
First, we define a Deque class that contains an internal array to store elements and provides methods for operating on these elements.
javascriptclass Deque { constructor() { this.items = []; } // Add element to the front of the deque addFront(element) { this.items.unshift(element); } // Add element to the back of the deque addBack(element) { this.items.push(element); } // Remove element from the front of the deque removeFront() { if (this.isEmpty()) { return undefined; } return this.items.shift(); } // Remove element from the back of the deque removeBack() { if (this.isEmpty()) { return undefined; } return this.items.pop(); } // Check if the deque is empty isEmpty() { return this.items.length === 0; } // Get the size of the deque size() { return this.items.length; } // Clear the deque clear() { this.items = []; } // View the front element front() { if (this.isEmpty()) { return undefined; } return this.items[0]; } // View the back element back() { if (this.isEmpty()) { return undefined; } return this.items[this.items.length - 1]; } }
Usage Example
Here are some examples of using the Deque class:
javascriptlet deque = new Deque(); // Add elements deque.addBack(1); deque.addBack(2); deque.addFront(0); console.log(deque.items); // [0, 1, 2] // Remove elements console.log(deque.removeFront()); // 0 console.log(deque.removeBack()); // 2 console.log(deque.items); // [1] // Check functionality console.log(deque.isEmpty()); // false console.log(deque.size()); // 1 console.log(deque.front()); // 1 console.log(deque.back()); // 1 // Clear the deque deque.clear(); console.log(deque.isEmpty()); // true
In this implementation, we leverage JavaScript array methods push, pop, shift, and unshift to simplify the implementation of addBack, removeBack, removeFront, and addFront, which respectively handle adding and removing elements from the end and beginning of the array.
2024年6月29日 12:07 回复