Topic:
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list 1 -> 2 -> 3 -> 4 is and you were given the third node with value 3 , the linked list should become 1 -> 2 -> 4 a Fter calling your function.
Solving:
This morning inadvertently see the list there is a problem easy did not do, decisive to do, see the topic, feel this problem is a bit like brain teasers, it asked to delete a link list of a node, and only to that node, not to other information, but also said that the node will not be the last node.
The idea is to overwrite the node that you want to delete with the value of the node's next node, and then delete the next node.
Code:
public void Deletenode (ListNode node) {node.val=node.next.val;node.next=node.next.next; }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode237_delete node in a Linked list (deleting nodes in a linked list) Java puzzle