链表中去掉重复数字

93 阅读1分钟

一个链,node的格式为

function Node(value, next) {
  this.value = value
  this.next = next || null
}

去掉所有重复的节点,返回一个新链。比如 1->1->2->3->3->5->5->5->7 返回 2->7

解题:



function Node(value, next) {
  this.value = value
  this.next = next || null
}

function createList(arr) {
  if (arr.length === 1) {
    return new Node(arr[0])
  }
  return new Node(arr[0], createList(arr.slice(1)))
}

function Printlist(node) {
  for (; node;) {
    console.log(node.value)
    node = node.next
  }
}

function removeRepeatNode(node) {
  let preHead = new Node(null, node)
  let preNode = preHead
  let tempNode = node
  let repeatValue = false

  for (; tempNode;) {
    if (tempNode.value === tempNode.next?.value || repeatValue === tempNode.value) {
      repeatValue = tempNode.value
      preNode.next = tempNode.next;
    } else {
      preNode = tempNode
    }
    tempNode = tempNode.next;
  }
  Printlist(preHead.next)
}

const list1 = createList([1, 1, 2, 3, 3, 4, 4, 5, 5])
removeRepeatNode(list1)