问题:
难度:easy
说明:
水题,给一个需要删除的单链表节点,然后删除,不用返回任何值。
输入案例:
Example 1:
// 原来是 4 5 1 9 然后输入一个节点 5 ,删除之后就只有 4 1 9
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
我的代码:
单链表删除的话总是想到从头开始遍历,然后找到需要删除的节点,把 target.prev.next = target.next,不过只给出需要删除的节点不给头结点的话需要如何删除?其实也简单,把内容复制,最后一个节点置空就行。
class Solution {
public void deleteNode(ListNode node) {
ListNode prev = new ListNode(-1);
// 弄个前置的节点
prev.next = node;
while(node.next != null) {
ListNode temp = node.next;
// 把下一个节点值复制到前一个
node.val = temp.val;
prev = node;
node = temp;
}
// 将最后一个节点置空
prev.next = null;
}
}
其它代码:
才没有其他代码,水题,100%RT