diff --git a/src/linked-list.js b/src/linked-list.js index 267e295..031cbda 100644 --- a/src/linked-list.js +++ b/src/linked-list.js @@ -9,17 +9,39 @@ class LinkedList { // If the list is empty, the new element is considered the tail as well as the head // If there is one element in the list before the new element is added, the new element becomes the tail of the list addToTail(value) { - + const node = { + next: null, + value, //abbreviated as value, + }; + if (this.tail === null) { + this.tail = node; + this.head = node; + return; + } + const oldTail = this.tail; + oldTail.next = node; + this.tail = node; } // Removes the current head node from the list, replacing it with the next element in the list // Returns the value of the removed node removeHead() { - + if (this.head == null) return null; + const oldHead = this.head; + this.head = oldHead.next; + if (this.head === null) { + this.tail = null; + } + return oldHead.value; } // Checks the linked list for the given value // Returns true if the the value is found in the list, false otherwise contains(value) { - + let node = this.head; + while (node != null) { + if (node.value === value) { return true; } + node = node.next; + } + return false; } } diff --git a/src/queue.js b/src/queue.js index dcf7ad7..e87e34c 100644 --- a/src/queue.js +++ b/src/queue.js @@ -5,6 +5,24 @@ 4. Add a `dequeue` method that removes the item in the queue that was added earliest */ class Queue { + constructor() { + this.storage = []; + this.count = 0; + } + enqueue(item) { + this.storage.push(item); + this.count++; + } + dequeue() { + if (this.count === 0) { + return 0; + } + this.count--; + return this.storage.shift(); + } + get size() { + return this.count; + } } diff --git a/src/stack.js b/src/stack.js index 4312b41..1fa636d 100644 --- a/src/stack.js +++ b/src/stack.js @@ -1,11 +1,36 @@ /* - 1. Add a constructor with a storage structure; there are multiple options you could use for this + o1. Add a constructor with a storage structure; there are multiple options you could use for this + sizeGetter () { + return this.size; + } + 2. Add a size getter that returns the number of items the stack is storing + this.storage = {}: 3. Add a `push` method that accepts an item as input and adds it to the storage structure + pushToStack(item) this.storage=item 4. Add a `pop` method that removes the most recently-added item to the stack */ class Stack { + constructor() { + this.storage = []; + this.count = 0; + } + + get size() { + return this.count; + } + push(value) { + this.storage[this.count] = value; + this.count++; + } + pop() { + const item = this.storage[this.count - 1]; + if (this.count === 0) { return null; } + delete this.storage[this.count - 1]; + this.count--; + return item; + } } module.exports = Stack;