237. Delete Node in a Linked List

237. Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

note:

  • The linked list will have at least two elements.
  • All of the nodes' values will be unique.
  • The given node will not be the tail and it will always be a valid node of the linked list.
  • Do not return anything from your function.

虽说是Easy难度的题目,但是拿到手的时候看不到难度,第一反应却是这不可能做出来。
没有头节点来进行遍历,只有目标节点我如何拿到目标节点的上一个结点呢?
答案是转变思路,这里我们要做的不是直接将该节点从链表中摘除,而是删除目标节点的下一个节点,并把节点中的值和next赋给当前结点就行了。
简简单单两行代码就能做完的事,结果想了十五分钟。

var deleteNode = function(node) {
    node.val = node.next.val;
    node.next = node.next.next;
};

做完以后到题目的solution下面看了一下,看来被唬住的不止我一个。


image.png

你可能感兴趣的:(237. Delete Node in a Linked List)