题目简介
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
自己的解法
/**
* 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) {
node.val = node.next.val;
node.next = node.next.next;
}
}
Hot解法的思路也和我的解法基本相同。这里不作分析。
本文详细解释了如何通过直接修改给定节点的值来删除单链表中的非尾部节点,避免了传统的需要保存前一个节点的方法。通过实例演示了在不同链表情况下的应用,并讨论了此方法的效率和适用场景。
1092

被折叠的 条评论
为什么被折叠?



