/*
Code_Listing of the Doubly Linked List
*/
/*
main function List
*/
function List() {
this._length = 0;
this._head = null;
this._tail = null;
}
List.prototype = {
head: function() {
return this._head.data;
},
tail: function() {
return this._tail.data;
},
append: function( data ) {
var node = {
data: data,
next: null,
prev: null
};
if ( this._length == 0 ) {
this._head = node;
node.prev = this._tail;
this._tail = node;
} else {
this._tail.next = node;
node.prev = this._tail;
this._tail = node;
}
this._length++;
return this;
},
deleteAt: function( index ) {
if ( index > -1 && index < this._length ) {
var current = this._head, i = 0;
if ( index === 0 ) {
this._head = current.next;
if ( !this._head ) {
this._tail = null;
} else {
this._head.prev = null;
}
} else if ( index === this._length - 1 ) {
current = this._tail;
this._tail = current.prev;
this._tail.next = null;
} else {
while ( i != index ) {
current = current.next;
i++;
}
current.prev.next = current.next;
current.next.prev = current.prev;
}
this._length--;
return this;
} else {
return null;
}
},
at: function( index ) {
if ( index > -1 && index < this._length ) {
var current = this._head, i = 0;
while ( i != index ) {
current = current.next;
i++;
}
return null;
}
},
insertAt: function( index, data ) {
var node = {
data: data,
next: null,
prev: null
};
if ( index > -1 && index < this._length + 1 ) {
var current = this._head, i = 0;
if ( this._length == 0 ) {
this._head = node;
this._tail = node;
} else if ( index === 0 ) {
this._head = node;
node.next = current;
current.prev = node;
} else if ( index === this._length ) {
current = this._tail;
current.next = node;
node.prev = current;
this._tail = node;
} else {
while( i != index ) {
current = current.next;
i++;
}
current.prev.next = node;
node.prev = current.prev;
current.prev = node;
node.next = current;
}
this._length++;
return this;
}
},
reverse: function() {
var current = this.head, tmp;
while ( current != null ) {
tmp = current.next;
current.next = current.prev;
current.prev = tmp;
current = current.prev;
}
tmp = this._head;
this._head = this._tail;
this._tail = tmp;
return this;
},
each: function( func ) {
var current = this._head;
while ( current != null ) {
current.data = func( current.data );
current = current.next;
}
return this;
},
indexOF: function( data ) {
var current = this._head, i = 0;
while ( current != null ) {
if ( current.data == data ) {
return i;
};
i++;
current = current.next;
}
return null;
}
};