237. 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指向其后置节点的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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容