237. Delete Node in a Linked List

来源:互联网 发布:sublime text mac破解 编辑:程序博客网 时间:2024/06/09 18:50

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所指的结点这种删除结点的方法。考虑将删除结点的下一个结点的val覆盖该删除结点的val,然后修改该删除结点的next指向该删除结点的下一个结点的next(即该删除结点的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) {        if(node.next!=null){            node.val = node.next.val;            if(node.next.next!=null)                node.next = node.next.next;            else                node.next = null;        }    }}