1. 程式人生 > >LeetCode oj 237. Delete Node in a Linked List (連結串列)

LeetCode oj 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.

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 -> 4after calling your function.

給你一個連結串列中的節點,讓你刪除這個節點。

按照正常寫法,刪除一個節點要知道這個節點的前驅和後繼,但是現在只告訴你這個節點了,那麼我們就把這個節點的後繼節點的值複製過來,然後刪除後繼節點就可以了

/**
 * 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) {
        ListNode temp = node.next;
        node.val = temp.val;
        node.next = temp.next;
        temp.next = null;
    }
}