LeetCode笔记:237. Delete Node in a Linked List
程序员文章站
2024-02-17 10:36:28
...
题目:
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.
大意:
写一个函数来删除一个简单链表中的一个节点(除了尾节点),只给出这个节点。
假设有一个链表 1->2->3->4,并给你第三个值为3的节点,在调用你的函数之后这个链表应该变成1->2->4。
思路:
一般我们删除一个链表节点,直接将其上一个节点的next指向其下一个节点就可以了,但是这里只给出了该节点本身,也就是说你只能获取到该节点本身以及其下一个节点。那么就只能将该节点直接变成下一个节点了,将其值设为下一个节点的值,将其next指向下一个节点的next,就可以了。
代码(Java):
/**
* 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;
}
}
代码(C++):
/**
* 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 = *node->next;
}
}
疑问:
用Java像C++那样,直接将 node = node.next 将不能ac,必须对其val和next分别设置,这是为什么呢?希望高手帮忙解答一下~
合集:https://github.com/Cloudox/LeetCode-Record
上一篇: LeetCode 66. 加一
下一篇: 查看路由表
推荐阅读
-
237. Delete Node in a Linked List
-
LeetCode笔记:237. Delete Node in a Linked List
-
237. Delete Node in a Linked List
-
LeetCode 237. Delete Node in a Linked List
-
237. Delete Node in a Linked List【力扣】
-
237. Delete Node in a Linked List
-
237. Delete Node in a Linked List
-
237. Delete Node in a Linked List
-
237. Delete Node in a Linked List
-
237. Delete Node in a Linked List