class Node {
	constructor(value) {
		this.value = value;
		this.next = null;
	}
}

class Deque {
	constructor() {
		this.head = null;
		this.tail = null;
		this.size = 0;
	}
	
	unshift(value) {
		if (this.head === null) {
			this.head = new Node(value);
			this.tail = this.head;
			this.size++;
			return;
		}
		
		let newNode = new Node(value);
		let current = this.head;
		
		this.size++;
		this.head = newNode;
		this.head.next = current;
	}
	
	shift() {
		if (this.head === null) return;
		if (this.head.next === null) {
			this.head = null;
			this.tail = null;
			this.size--;
			return;
		}
		
		this.size--;
		this.head = this.head.next;
	}
	
	push(value) {
		if (this.head === null) {
			this.head = new Node(value);
			this.tail = this.head;
			this.size++;
			return;
		}
		
		this.size++;
		this.tail.next = new Node(value);
		this.tail = this.tail.next;
	}
	
		pop() {
		if (this.head === null) return;
		if (this.head.next === null) {
			this.head = null;
			this.tail = null;
			this.size--;
			return;
		}
		
		let current = this.head;
		
		while(current.next.next) {
			current = current.next;
		}
		
		this.size--;
		current.next = null;
		this.tail = current;
	}
	
	isEmpty() {
		return this.head === null ? true : false;
	}
	
	get length() {
		return this.size;
	}

	clear() {
		this.head = null;
		this.tail = null;
		this.size = 0;
	}
}

+ Recent posts