Created
August 27, 2015 17:20
-
-
Save sergiorgiraldo/f1bae5e437c378f24310 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
function Item(value){ | |
this.value = value; | |
this.next = null; | |
} | |
function List(value) { | |
this.head = new Item(value); | |
this.tail = null; | |
this.length = 1; | |
this.add=function(value){ | |
var item = new Item(value); | |
if (this.tail == null){ | |
this.head.next = item; | |
} | |
else{ | |
this.tail.next = item; | |
} | |
this.tail = item; | |
this.length += 1; | |
} | |
this.itemAt=function(index){ | |
if (index >= this.length){ | |
return "no item in position " + index; | |
} | |
var curr = 0; | |
var item = this.head; | |
while (curr != index) | |
{ | |
item = item.next; | |
curr += 1; | |
} | |
return "item at position " + index + " equals " + item.value; | |
} | |
this.iterate = function(action){ | |
var item = this.head; | |
action(item.value); | |
while(item.next){ | |
item=item.next; | |
action(item.value); | |
} | |
} | |
this.print = function(){ | |
var began = false; | |
this.iterate(function(item){ | |
if (began) document.write(" => "); | |
document.write(item); | |
began = true; | |
}); | |
} | |
this.printReverse=function(){ | |
var itens = []; | |
this.iterate(function(item){ | |
itens.push(item); | |
}); | |
itens.reverse(); | |
for (var i=0;i<itens.length;i++){ | |
document.write(itens[i]); | |
if (i != itens.length-1) | |
document.write(" => "); | |
} | |
} | |
} | |
var list = new List(1); | |
list.add(22); | |
list.add(333); | |
list.add(4444); | |
list.add(55555); | |
list.print(); | |
document.write("<br>"); | |
list.printReverse(); | |
document.write("<br> we have " + list.length + " itens"); | |
document.write("<br> " + list.itemAt(10)); | |
document.write("<br> " + list.itemAt(0)); | |
document.write("<br> " + list.itemAt(1)); | |
document.write("<br> " + list.itemAt(3)); | |
document.write("<br> " + list.itemAt(list.length)); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment