Delete a node, only give access to that node.

来源:互联网 发布:多开分身软件 编辑:程序博客网 时间:2024/05/19 19:16

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 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

思路:Only access to that node, we can copy the value of next node to that node, and point to the next.next;

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public void deleteNode(ListNode node) {        if(node == null || node.next == null) {            return;        }        ListNode next = node.next;        node.val = next.val;        node.next = next.next;        return;    }}


0 0
原创粉丝点击