Удаление нечетных / четных чисел из связанного списка - PullRequest
1 голос
/ 13 октября 2019

Это стандартный связанный список с данными и следующими свойствами.

Это то, что я пытаюсь:

class Node {
    constructor(data, next) {
        this.data = data;
        this.next = next;
    }
}

class LinkedList {
    constructor() {
        this.head = null;
    }

    insertFirst(data) {
        this.head = new Node(data, this.head);
    }

    size() {
        let counter = 0, node = this.head;

        while (node) {
            counter++;
            node = node.next;
        }

        return counter;
    }

    toArray() {
        let node = this.head;
        const result = [];

        while (node) {
            result.push(node.data);
            node = node.next;
        }

        return result;
    }


    removeEven() {
        let previous = this.head;
        let node = this.head.next;

        if (this.isEven(previous.data)) {
            console.log('outside loop, found one: ' + previous.data)
            this.head = this.head.next;
        }

        while (node) {
            if (this.isEven(node.data)) { 
                console.log('found ' + node.data); 
                previous.next = node.next;
            }

            node = node.next;
        }

    }

    isEven(num) { return num % 2 === 0 ? true : false; }
}

const q = new LinkedList();
q.insertFirst(16)
q.insertFirst(3)
q.insertFirst(4)
q.insertFirst(7)
q.insertFirst(5)
q.insertFirst(2)
q.insertFirst(1)
q.insertFirst(15)
q.insertFirst(18)
q.removeEven();

console.log(q.toArray());

И вывод:

outside loop, found one: 18
found 2
found 4
found 16
[ 15, 1, 2, 5, 7, 4, 3, 16 ] 

Так что это только удаление первого значения, которое находится за пределами цикла, как я могу удалить другие значения?

РЕДАКТИРОВАТЬ: Добавлен полный код, однако, он просит меня добавить больше текста, и я неесть еще что добавить, кроме того, что я уже добавил.

Ответы [ 3 ]

0 голосов
/ 13 октября 2019

Вы довольно близки, вам нужно сохранить ссылку на последнее обновленное значение

class Node {
  constructor(data, next) {
    this.data = data;
    this.next = next;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
  }

  insertFirst(data) {
    this.head = new Node(data, this.head);
  }

  size() {
    let counter = 0,
      node = this.head;

    while (node) {
      counter++;
      node = node.next;
    }

    return counter;
  }

  toArray() {
    let node = this.head;
    const result = [];

    while (node) {
      result.push(node.data);
      node = node.next;
    }

    return result;
  }


  removeEven() {
    let current = this.head;
    let final;

    while (current.next) {
      if (this.isEven(current.data)) {
        current = current.next;
      } else {
        if (!final) {
          final = current
          this.head = final
        } else {
          final.next = current
          final = current
        }
        current = current.next
      }
    }
    if (this.isEven(current.data)) {
      final.next = null
    }
  }

  isEven(num) {
    return num % 2 === 0 ? true : false;
  }
}

const q = new LinkedList();
q.insertFirst(16)
q.insertFirst(3)
q.insertFirst(4)
q.insertFirst(7)
q.insertFirst(5)
q.insertFirst(2)
q.insertFirst(1)
q.insertFirst(15)
q.insertFirst(18)
q.removeEven();

console.log(q.toArray());
0 голосов
/ 13 октября 2019

class Node {
  constructor(data, next) {
    this.data = data;
    this.next = next;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
  }

  removeNodesWithNumberType(type = "isEven") {
    if (!this.head) return;
    let previousNode = this.head;
    let traversingNode = this.head;
    while (traversingNode) {
      if (this[type](traversingNode.data)) {
        this.removeNode(previousNode, traversingNode);
      } else {
        previousNode = traversingNode;
      }
      traversingNode = traversingNode.next;
    }
  }

  removeNode(previousNode, node) {
    if (this.isFirstNode(node)) this.head = node.next;
    previousNode.next = node.next;
  }

  isFirstNode(node) {
    return this.head === node;
  }

  isEven(num) {
    return num % 2 === 0;
  }

  isOdd(num) {
    return !this.isEven(num);
  }

  insertFirst(data) {
    this.head = new Node(data, this.head);
  }

  size() {
    let counter = 0,
      node = this.head;

    while (node) {
      counter++;
      node = node.next;
    }

    return counter;
  }

  toArray() {
    let node = this.head;
    const result = [];

    while (node) {
      result.push(node.data);
      node = node.next;
    }

    return result;
  }

  clear() {
    this.head = null;
  }
}

const q = new LinkedList();

// Test Case:1  Empty List
removeAndFormateOutput("isEven");

// Test Case:2  Single Node
q.insertFirst(16);
removeAndFormateOutput("isEven");

q.insertFirst(13);
removeAndFormateOutput("isOdd");

// Test Case:3 Two Consecutive Even
q.insertFirst(16);
q.insertFirst(18);
removeAndFormateOutput("isEven");

// Test Case:3 Two Consecutive odd
q.insertFirst(11);
q.insertFirst(13);
removeAndFormateOutput("isOdd");

// Test Case:4 Random List
q.insertFirst(3);
q.insertFirst(4);
q.insertFirst(7);
q.insertFirst(5);
q.insertFirst(2);
q.insertFirst(1);
q.insertFirst(15);
q.insertFirst(18);
q.insertFirst(20);
removeAndFormateOutput("isEven");

function removeAndFormateOutput(type) {
  console.log(`Remove if ${type} \n Before : ${q.toArray()}`);
  q.removeNodesWithNumberType(type);
  console.log(` After : ${q.toArray()}\n`);
  q.clear();
}
0 голосов
/ 13 октября 2019

Вы должны обновить previous в цикле.

class Node {
  constructor(data, next) {
    this.data = data;
    this.next = next;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
  }

  insertFirst(data) {
    this.head = new Node(data, this.head);
  }

  size() {
    let counter = 0,
      node = this.head;

    while (node) {
      counter++;
      node = node.next;
    }

    return counter;
  }

  toArray() {
    let node = this.head;
    const result = [];

    while (node) {
      result.push(node.data);
      node = node.next;
    }

    return result;
  }

  removeEven() {
    let previous = this.head;
    let node = this.head.next;

    if (this.isEven(previous.data)) {
      console.log('outside loop, found one: ' + previous.data)
      this.head = this.head.next;
    }

    while (node) {
      if (this.isEven(node.data)) {
        console.log('found ' + node.data);
        previous.next = node.next;
      } else {
        previous = node;
      }
      node = node.next;
    }

  }

  removeOdd() {
    let previous = this.head;
    let node = this.head.next;

    if (!this.isEven(previous.data)) {
      console.log('outside loop, found one: ' + previous.data)
      this.head = this.head.next;
    }

    while (node) {
      if (!this.isEven(node.data)) {
        console.log('found ' + node.data);
        previous.next = node.next;
      } else {
        previous = node;
      }
      node = node.next;
    }

  }

  isEven(num) {
    return num % 2 === 0 ? true : false;
  }
}

const q = new LinkedList();
q.insertFirst(16)
q.insertFirst(3)
q.insertFirst(4)
q.insertFirst(7)
q.insertFirst(5)
q.insertFirst(2)
q.insertFirst(1)
q.insertFirst(15)
q.insertFirst(18)
q.removeOdd();

console.log(q.toArray());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...