Original title Link: https://leetcode.com/problems/delete-node-in-a-linked-list/
Title Description:
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 Is 3
, the linked list should become 1, 2-4
after calling your function.
Ideas:
There are two ways to delete a linked list node, one is to change the pointer, not to change the node value, and to change the node value.
Conditions only give the pointer to delete the node p, not to the head node, so can not get the pre-node p, it is not easy to let the pre point to the node after p to complete the operation of delete P.
Therefore, only through the operation of the node value to achieve the purpose of deletion. Note that this method cannot delete the last node (which can be deleted from the head node). Fortunately, the topic only requires the deletion of intermediate nodes.
Algorithm:
[Java]View PlainCopy
- public   void deletenode (ListNode node) {
- listnode pre = node, p = node;
- while (p.next != null // when P is not the last node   
- P.val = P.next.val;
- Pre = P;
- p = p.next;
- }
- pre.next = null / / this time the pre points to the penultimate node
- }
"Leetcode" Delete Node in a Linked List