JSFiddle - React, Tailwind, and code Playground

by leiperte

HTML

<input type="button" id="createList" value="Create List" onClick="createList();" /> <br /> <br /> <input type="textbox" id="LinkName" value="New Node" /> <input type="button" id="AddLink" value="Add to List" onClick="addNode();" />
<p id="demo">
</p>

JavaScript

var list = null;

function createList() {
	list = new List('A');
  list.addNode('B');
  list.addNode('C');
  list.addNode('D');
  list.addNode('E');
  document.getElementById("demo").innerHTML = list.print();
}

function addNode() {
  var value = document.getElementById("LinkName").value;
  list.addNode(value);
  document.getElementById("demo").innerHTML = list.print();
}

function Node(_value, _prev) {
  this.value = _value;
  this.prev = _prev;
  this.next = null;
  return this;
}
Node.prototype.aString = function() {
  return this.value + " : ";
}

function List(_value) {
  this.length = 1;
  this.head = new Node(_value, null);
  this.tail = this.head;
}
List.prototype.addNode = function(_value) {
  var node = new Node();
  node.value = _value;
  if (this.head == null) {
    this.head = node;
    this.length = 1;
    return node;
  }
  if (this.tail == null) {
    this.tail = node;
    this.tail.prev = this.head;
    this.head.next = this.tail;
    this.length = 2;
    return node;
  }
  this.tail.next = node;
  node.prev = this.tail;
  this.tail = node;
  this.length++;
  return node;
}
List.prototype.print = function() {
  var s = "";
  var n = this.head;
  while (n != null) {
    s += n.aString();
    n = n.next;
  }
  return s;
}