题目描述
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) {
//先让该结点的值等于下一个结点的值12345->12445
node.val = node.next.val;
//再把下一个结点删除12445->1245
node.next = node.next.next;
}
}
主要思路
很简单,只需要把当前结点的值复制为下一个结点的值,然后删除下一个结点,就相当于把当前结点删除了
网友评论