链表具有偶数,奇数

时间:2019-03-09 11:32:39

标签: javascript algorithm

我在javascript中有一个链表。

但是现在我想在一个数组中具有偶数的indexOf,在另一个数组中具有奇数的indexOf。

我这样尝试:

function linkedList() {
    this.head = null;
    this.tail = null;
}

function Node(value, next, prev) {
    this.value = value;
    this.next = next;
    this.prev = prev;
}
linkedList.prototype.addToHead = function (value) {
    var newNode = new Node(value, this.head, null);
    if (this.head) this.head.prev = newNode;
    else this.tail = newNode;
    this.head = newNode;
}

linkedList.prototype.addToTail = function (value) {
    var newNode = new Node(value, null, this.tail);
    if (this.tail) this.tail.next = newNode;
    else this.head = newNode;
    this.tail = newNode;
};

linkedList.prototype.search = function (searchValue) {
    var currentNode = this.head;
    while (currentNode) {
        if (currentNode.value === searchValue)
            return currentNode.value;
    }
    return null;
};

linkedList.prototype.indexOfMethod = function () {

    var indexofValuesEven = [];
    var indexValuesOdd = [];
    var currentINdex = 0;

    var currentNOde = this.head;
    while (currentNOde) {
        if (currentNOde.value % 2 === 0) {
            indexofValuesEven.push(currentINdex);
            // return indexofValuesEven;
        } else if (currentNOde.value % 2 != 0) {
            indexValuesOdd.push(currentINdex);
            // return indexValuesOdd;
        }
        currentNOde = currentNOde.next;
        currentINdex++;

    }

    return indexValuesOdd, indexofValuesEven;

}



ll = new linkedList();


ll.addToTail(1);
ll.addToTail(2);
ll.addToTail(3);
ll.addToTail(4);
ll.addToTail(4);


console.log(ll.indexOfMethod()); 

但是现在我只在一个数组中获得偶数的indexOf。我了解,重审声明看起来不正确。但是我不知道该如何更改。

那我要改变什么?

谢谢

0 个答案:

没有答案