LeetCode -- Delete Node in a Linked List
Question:
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.
Analysis:
题目只给出要删除的节点外没有给出任何其他信息。但是在单链表中我们知道,要删除一个节点,必须给出上一个节点。在这里,题目只给出了目前节点,因此我们可以删除的只有它后面的节点。因此思路就是:想办法把后面节点变为我们要删除的节点。用后面一个节点的值覆盖当前节点的值,这样后面的节点就成来没用的废气节点,然后删除即可。
Answer:
/** * 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.next.next == null){ node.val = node.next.val; node.next = null; } else { node.val = node.next.val; node.next = node.next.next; } } }