Skip to content
Cheng Lou edited this page Jun 27, 2013 · 4 revisions

Doubly Linked.

Overview example:

var list = new LinkedList([5, 4, 9]);
list.add(12); // => 12
list.head.next.value; // => 4
list.tail.value; // => 12
list.at(-1); // => 12
list.removeAt(2); // => 9
list.remove(4); // => 4
list.indexOf(5); // => 0
list.add(5, 1); // => 5. Second 5 at position 1.
list.indexOf(5, 1); // => 1

Properties:

  • head: first item.
  • tail: last item.
  • size: total number of items.
  • item.value: value passed to the item when calling add().
  • item.prev: previous item.
  • item.next: next item.

Instance Methods

Can pass an array of elements to link together during new LinkedList() initiation.

Get the item at position (optional). Accepts negative index:

myList.at(-1); // Returns the last element.

However, passing a negative index that surpasses the boundary will return undefined:

myList = new LinkedList([2, 6, 8, 3])
myList.at(-5); // Undefined.
myList.at(-4); // 2.

Returns: item gotten, or undefined if not found.

Add a new item at position (optional). Defaults to adding at the end. position, just like in at(), can be negative (within the negative boundary). Position specifies the place the value's going to be, and the old node will be pushed higher. add(-2) on list of size 7 is the same as add(5).

Returns: item added.

Remove an item at index position (optional). Defaults to the last item. Index can be negative (within the boundary).

Returns: item removed.

Remove the item using its value instead of position. Will remove the fist occurrence of value.

Returns: the value, or undefined if value's not found.

Find the index of an item, similarly to array.indexOf(). Defaults to start searching from the beginning, by can start at another position by passing startingPosition. This parameter can also be negative; but unlike the other methods of this class, startingPosition (optional) can be as small as desired; a value of -999 for a list of size 5 will start searching normally, at the beginning.

Note: searches forwardly, not backwardly, i.e:

var myList = new LinkedList([2, 3, 1, 4, 3, 5])
myList.indexOf(3, -3); // Returns 4, not 1

Returns: index of item found, or -1 if not found.