我正在上一个数据结构类,我必须使用Jsfiddle来演示我的作业

时间:2017-02-08 22:02:18

标签: javascript html list data-structures

我需要创建一个接口以允许用户将节点添加到列表中。到目前为止,这是我的代码,不确定我做错了什么我是新的。

当我试图在jsfiddle编辑器中运行它时没有输出?我在代码中运行它,并且错误表示id未定义。这是我小提琴的链接:http://jsfiddle.net/liamtsw/hzvwnxh0/8

HTML

   <br/>
   <br/> Name of Node being added:
   <input type="textbox" id="LinkName" Value="New Node" />
    <input type="button" id="CreateList" value="Create List"        onClick="createList();" />
     <input type="button" id="AddLink" value="Add Node to List"       onClick="addNode();" />
    <p id="demo"></p>
     <br/>
   var list = null;

//a function for creating a list

  function createList() {

  var value = document.getElementById("LinkName").value;

 var length = document.getElementById("LinkName").length;

 list = new List(value, length);

 document.getElementById("demo").innerHTML = list.print();

}

//a function for adding a new node to list

  function addNode() {

 var id = document.getElementById("LinkName").id;

  var value = document.getElementById("LinkName").value;

  list.addNode(id, value);

 document.getElementById("demo").innerHTML = list.print();

}

// Define the link object with following properties

function Node(_id, _value, _last) {

   this.id = _id; // A simple id for the node itself

  this.value = _value; // The value stored

  this.last = _last; // A pointer to the previous link

  this.next = null; // a pointer to the next link

 return this; // returns the created node

}

Node.prototype.asString = function() {

  return "Node Value:" + this.value + "<br/>";

}

// Define the List object

 function List(_value, _length) {

// We will define the list with the first link defined

this.length = _length;

 this.head = new Node(_id, _value, null); // Pointer TO the head is null

this.last = this.head; // When created - head and last are the same.

}

 List.prototype.addNode = function(_value) {

 var node = new Node(_id, _value, _last);

if (this._length) {

  this.last.next = node;

  node.last = this.last;

   this.last = node;

 }    else 
{

      this.head = node;

  this.last = node;

}

   this._length++;

    return node;

}

//print function

   List.prototype.print = function()

{

   var s = "";

  var n = this.head;

while (n != null) {

   s += n.asString();

  n = n.next;

 }

   return s;

}

   //create data structure object
 var _list = new createList();

 //add nodes
  var node = new Node(_id, _value, _last);
  node.id = 1;

   node.value = "A";
 _list.addNode(node);

  var node = new Node(_id, _value, _last);
  node.id = 2;

   node.value = "B";
  _list.addNode(node);

 var node = new Node(_id, _value, _last);
 node.id = 3;

 node.value = "C";
_list.addNode(node);

 var node = new Node(_id, _value, _last);
 node.id = 4;

 node.value = "D";
 _list.addNode(node);

 var node = new Node(_id, _value, _last);
  node.id = 5;

  node.value = "E";
 _list.addNode(node);

  _list.print();


<p id="demo"></p>

<p id="addNode2"></p>

0 个答案:

没有答案