Data Structures Practice

Linked Lists Stacks

by ClarenceDowns

HTML

<h3>
  Stack
</h3>
<p>
  Stack /stak:/</br>
  1. a pile of objects, typically one that is neatly arranged.
</p>
<ol>
  <li>Push</li>
  <li>Pop</li>
  <li>Peek</li>
  <li>Reverse</li>
  <li>Length</li>
  <li>Search</li>
  <li>IsEmpty</li>
  <li>Traverse</li>
</ol>
<h3>
  Queue
</h3>
<p>
  queue /kju:/</br>
  1.a list of data items, commands, etc., staored so as to be retrievable in a definite order, usually the order of insertion.
</p>
<ol>
  <li>Enqueue</li>
  <li>Dequeue</li>
  <li>Length</li>
  <li>Peek</li>
  <li>IsEmpty</li>
  <li>Traverse</li>
</ol>
</br>
</br>

JavaScript

//Singly Linked Lists
function List() {
  this.head = null;
  this.length = 1;
}

List.prototype.push = function(_val) {
  node = {
    value: _val,
    next: null
  }
  if (!this.head) {
    this.head = node;
  } else {
    var current = this.head;
    while (current.next) {
      current = current.next
    }
    current.next = node;
    this.length++;
  }
}

List.prototype.pop = function() {

}
let list = new List();
list.push('One');
list.push('Two');
list.push('Three');
list.push('Four');
console.log(list);

//Stack
function Stack() {
  this.top = null;
  this.length = 0;
}
//Push function
Stack.prototype.push = function(_val) {
  var node = {
    value: _val,
    next: null
  }
  if (this.top) {
    node.next = this.top;
    this.top = node;
  } else {
    this.top = node;

  }
  this.length++;
}
// Pop function
Stack.prototype.pop = function() {
  if (this.top) {
    var itemToPop = this.top;
    this.top = this.top.next;
    this.length--;
    return itemToPop.value;
  } else {
    console.log('Stack is empty!');
    return false;
  }
}

//Peek function
Stack.prototype.peek = function() {
  if (this.top) {
    return this.top.value;
  } else {
    return null;
  }
}

//Reverse function
Stack.prototype.reverse = function() {
  let current = this.top;
  let prev = null;
  while (current) {
    let next = current.next;
    current.next = prev;
    prev = current;
    current = next;
  }
  this.top = prev
}

//Length, Search & IsEmpty
Stack.prototype.length = function() {
  let current = this.top;
  let counter = 0;
  while (current) {
    counter++;
    current = current.next;
  }
  return counter;
}

Stack.prototype.search = function(_item) {
  let current = this.top;
  while (current) {
    if (current === _item) return true
    current = current.next;
  }
  return false
}

Stack.prototype.isEmpty = function() {
  return this.length > 1;
}

//traverse function. This takes a call back function as its parameter
// ex: to add 10 to all odd numbers in the...