【问题标题】:removing the duplicates of a linked list javascript删除链表javascript的重复项
【发布时间】:2021-05-13 17:25:55
【问题描述】:

这是我迄今为止比较节点的代码:

const removeDuplicates = (headNode) => { 
  let cur = headNode;
  while (cur.next) {
    let nextnode = cur.next;
    if (cur.data == nextnode.data) {
      cur.next = cur.next.next;
    } else {
      cur = cur.next;    
    }
  }
  return headNode;
}

如果列表是[1, 2, 1, 3, 4, 2, 1] => [1, 2, 3, 4]

第四个节点应该是 4 却得到了 1,为什么?
我该如何解决这个问题?

【问题讨论】:

  • 类和函数没有关系
  • 您使用 JavaScript Set 对象从数组中删除重复项,例如console.log([...new Set(arr)]);

标签: javascript class linked-list duplicates


【解决方案1】:

当前您正在检查 2 个相邻节点,如果这 2 个相邻节点彼此不相等,则会错过其他节点,例如 [1, 2, 1, 2, 1] 的情况

一个解决方案是设置一个检查数据是否被访问过的集合

const removeDuplicates = (headNode) => {
  let cur = headNode;
  let visited = new Set([cur.data]);
  while (cur.next) {
    let nextnode = cur.next;
    if (visited.has(nextnode.data)) {
      // if current node data is visited, skip
      cur.next = nextnode.next;
    } else {
      // if current node data is not visited, visit
      visited.add(nextnode.data);
      cur = nextnode;
    }
  }
  return headNode;
};

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

const removeDuplicates = (headNode) => {
  let cur = headNode;
  let visited = new Set([cur.data]);
  while (cur.next) {
    let nextnode = cur.next;
    if (visited.has(nextnode.data)) {
      // if current node data is visited, skip
      cur.next = nextnode.next;
    } else {
      // if current node data is not visited, visit
      visited.add(nextnode.data);
      cur = nextnode;
    }
  }
  return headNode;
};

// prepare data
const arr = [1, 2, 1, 3, 4, 2, 1];
let head, prevNode;
while (arr.length > 0) {
  let node = new Node(arr.pop());
  if (prevNode) {
    node.next = prevNode;
  }
  head = node;
  prevNode = node;
}

// remove duplicate
const headAfterRemove = removeDuplicates(head);

// verify result
let cursor = headAfterRemove;
while (cursor) {
  console.log(cursor.data);
  cursor = cursor.next;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    相关资源
    最近更新 更多