LinkedList - 2

by jessekinsman

HTML

<link rel="stylesheet" href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css">
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.2/react-dom.js"></script>
<div id='target'>no snapshots</div>

CSS

td {
  color: white;
  padding: 5px;
  text-align: center;
}

table {
  margin-bottom: 10px;
}

Babel + JSX

/*
  LinkedList
  
  Name your class / constructor (something you can call new on) LinkedList
  
  LinkedList is made by making nodes that have two properties, the value that's being stored and a pointer to
  the next node in the list. The LinkedList then keep track of the head and usually the tail (I would suggest
  keeping track of the tail because it makes pop really easy.) As you may have notice, the unit tests are the
  same as the ArrayList; the interface of the two are exactly the same and should make no difference to the
  consumer of the data structure.
  
  I would suggest making a second class, a Node class. However that's up to you how you implement it. A Node
  has two properties, value and next.
  
  length - integer  - How many elements in the list
  push   - function - accepts a value and adds to the end of the list
  pop    - function - removes the last value in the list and returns it
  get    - function - accepts an index and returns the value at that position
  delete - function - accepts an index, removes value from list, collapses, 
                      and returns removed value

  As always, you can change describe to xdescribe to prevent the unit tests from running while
  you work
*/

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

class LinkedList {
	constructor() {
  	this.length = 0;
    this.head = null;
    this.tail = null;
  }
  push(value) {
  const node = new Node(value);
  	if (!this.head) {
    	this.head = node;
      this.tail = node;
    } else {
    	this.tail.next = node;
    	this.tail = node; 
    }
    this.length++;
  }
  pop() {
  	console.log("length " + this.length);
		let node = this.head;
    for (let i = 0; i < this.length-2; i++) {
    	node = node.next;
    }
    this.tail = node;
    if (node.next) {
    	node = node.next;
      this.tail.next = null;
    } else {
    	this.head = null;
      this.tail = null;
    }
    this.length--;
    return node.value;
  }
 ...