237. Delete Node in a Linked List
程序员文章站
2024-02-17 10:18:52
...
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指向其后置节点的next
题解
/**
* 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) {
int temp = node.next.val;
node.next.val = node.val;
node.val = temp;
node.next = node.next.next;
}
}