1 题目描述
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.
2 解题思路
2.1题目类型属于单链表,但只给了该节点,不知道前一个节点,坑爹啊,因此考虑将下一个节点的值赋给该节点,然后删除下一个节点。
3 源代码
package com.larry.easy;
import com.larry.util.ListNode;
public class DeleteNodeInALinkedList {
public void deleteNode(ListNode node) {
if(node == null) return;
node.val = node.next.val;
node.next = node.next.next;
}
}