Delete Node in the Middle of Singly Linked List(在O(1)时间复杂度删除链表节点 )

问题

Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.
Example
Linked list is 1->2->3->4, and given node 3, delete the node in place 1->2->4

分析

因为没有node的前边的那个节点,所以node本身是无法删除的(原理请参阅 翻转链表)。所以这个问题是只需要保证结果是对的即可,我们首先把node的下一个节点的值复制到node上边,然后删除node的下一个节点就可以了。

代码

 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param node: the node in the list should be deleted
     * @return: nothing
     */
    public void deleteNode(ListNode node) {
        // write your code here
        if(node==null||node.next==null){
            return;
        }
        node.val=node.next.val;
        node.next=node.next.next;
    }
}

你可能感兴趣的:(Delete Node in the Middle of Singly Linked List(在O(1)时间复杂度删除链表节点 ))