美文网首页
删除链表的节点

删除链表的节点

作者: 曾大稳丶 | 来源:发表于2022-05-11 18:48 被阅读0次

    题目链接: https://leetcode.cn/problems/shan-chu-lian-biao-de-jie-dian-lcof/

    image.png

    题目解析
    使用双指针。遍历记录precur当前节点,同时判断当前val是否匹配,如果匹配就跳出循环。

    public ListNode deleteNode(ListNode head, int val) {
            if (head.val == val) return head.next;
            ListNode pre=head,cur = head.next;
            while (cur!=null && cur.val != val){
                pre = cur;
                cur = cur.next;
            }
            if (cur!=null) pre.next = cur.next;
            return head;
    }
    

    复杂度分析
    空间复杂度: O(1)。
    时间复杂度: O(N)。

    相关文章

      网友评论

          本文标题:删除链表的节点

          本文链接:https://www.haomeiwen.com/subject/nscjurtx.html