Prosta implementacja listy w JavaScript
Kod jest bardzo prosty:
List = function(h){
if (h) {
if (this.setHead(h)) this.tail = h;
}
}
ListElement = function(val) {
this.value = val;
this.next = null;
this.prev = null;
}
ListElement.prototype.setNext = function(l) {
if (!l || l.constructor != ListElement) return false;
this.next = l;
l.prev = this;
return l;
}
List.prototype.setHead = function(l){
if (!l || l.constructor != ListElement) return false;
this.head = l;
l.prev = l;
return l;
}
List.prototype.iterate = function(func) {
var elem = this.head;
while (elem !== null) {
func.apply(this, [elem.value]);
elem = elem.next;
}
}
Jak używać ? Przykład:
// najpierw tworzymy elementy listy
l1 = new ListElement("one");
l2 = new ListElement("drugi element listy");
l3 = new ListElement("i trzeci ... ");
// ustawiamy kolejność
l1.setNext(l2).setNext(l3);
// a teraz tworzymy sam obiekt
lst = new List;
lst.setHead(l1);
// i jakieś konkretne wykorzystanie, zeby było wiadomo, że działa ;)
lst.iterate(function(val){ alert(val); });
