Leetcode 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.

本题只给出需要删除的节点,前置节点,链表头节点都没有给出,所以无法直接删除。只能从删除结点开始,将后面节点的值依次向前挪。

我的解法:

遇到问题:while的终止条件需提前一个节点,否则无法删除最后一个节点。之前写的while(after != null)

public class Solution {
    public void deleteNode(ListNode node) {
        ListNode now = node;
        ListNode after = node.next;
        
        while(after.next != null){
            now.val = after.val;
            now = now.next;
            after = after.next;
        }
        
        now.val = after.val;
        now.next = null;
        
    }
}



discuss里的简单解法:

问题:没有判定条件,循环不会一直执行吗?

public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
}


阅读更多
上一篇Leetcode 283. Move Zeroes
下一篇Leetcode 100. Same Tree
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭