practice4

by Ron Eaglin

HTML

<br>Create a double linked list and add new nodes.<br/>
Nodes are used as a stack calculator performing simple math with +, -, *, and /.<br/><br/>
<input type="textbox" id="NewNode" value="10" />
<input type="button" value="Add Node" onclick="addNode()"/>
<div id="output"></div>
<div id="error1"></div>
<div id="error2"></div>
<div id="result"></div>

JavaScript

//defines list head and tail as null
function createList() {
  this.head = null;
  this.tail = null;
}

//grabs user input value, initalize node counter to zero, print results
function addNode() {
  i = 1; //initiate LL at 1
  var getValue = document.getElementById("NewNode").value;
  myList.addNode(getValue);
  document.getElementById("output").innerHTML = myList.print();
}

//defines node pointers and keeps track of node numbers
function newNode() {
  this.next = null;
  this.last = null;
}

createList.prototype.addNode = function(_string) {
  //passes user input through function
  var node = new newNode();
  node.string = _string;
  var length;
  var position = this.head;

  //logical OR grabs operands when entered
  if (_string == '+' || _string == '-' || _string == '*' || _string == '/') {
    if (this.length >= 2) {
      this.doMath(_string);
    } else if (length < 2) {
      document.getElementById("error1").innerHTML = "Not Enough Items in the stack"; //needs fixing
    } else if (isNaN(_string)) {
      document.getElementById("error2").innerHTML = "Not a numerical value"; //needs fixing
      return;
    }

  } else {
    length = 1;
    if (this.head == null) {
      this.head = node;
      this.length = 1;
      return node;
    }
    while (position.next != null) {
      position = position.next;
      length++;
    }

    position.next = node;
    node.last = position;
    length++;
    this.length = length;

  }
}

createList.prototype.print = function() {
  var d = "";
  var e;
  var node = this.head;

  while (node != null) {
    d += i + ": " + node.string + "<br>";
    var e = "<br>Stack size is " + i;
    node = node.next;
    i++;
  }
  return d + e;
}

var myList = new createList();

//////////////////////////////////////////////////////////////////////


createList.prototype.doMath = function(_math) {
  var a = myStack.pop();
  var b = myStack.pop();
  var res = 0;

  this.length--;

  //perform arithmetic...
  switch (_math) {
    case...