题目链接:https://leetcode.com/problems/delete-node-in-a-linked-list/
题目: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.
解题思路:删除单链表中指定的节点,一般有两种方法:第一种是遍历得到指定节点的前一个节点,将该节点的next执行指定节点的下一个节点,然后删除指定节点,第二个方法是将指定节点下一个节点的data值赋给指定节点,然后将指定节点的next指向该节点的下下一个节点即可。本题显然可以使用第二种方法来解决。
示例代码:
public class Solution { class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public void deleteNode(ListNode node) { if(node==null) return ; node.val=node.next.val; node.next=node.next.next; } }
时间: 2025-01-07 19:22:49