

JZ-069-在 O(1) 时间内删除链表节点
source link: https://segmentfault.com/a/1190000041450918
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JZ-069-在 O(1) 时间内删除链表节点
在 O(1) 时间内删除链表节点
在 O(1) 时间内删除链表节点。
方案:如果该节点不是尾节点,那么可以直接将下一个节点的值赋给该节点,然后令该节点指向下下个节点,再删除下一个节点,时间复杂度为 O(1)。否则,就需要先遍历链表,找到节点的前一个节点,然后让前一个节点指向 null,时间复杂度为 O(N)。
题目链接: [在 O(1) 时间内删除链表节点]()
/** * 在 O(1) 时间内删除链表节点 */ public class Jz69 { /** * 方案: * 如果该节点不是尾节点,那么可以直接将下一个节点的值赋给该节点,然后令该节点指向下下个节点,再删除下一个节点,时间复杂度为 O(1)。 * 否则,就需要先遍历链表,找到节点的前一个节点,然后让前一个节点指向 null,时间复杂度为 O(N)。 * * @param head * @param tobeDelete * @return */ public ListNode deleteNode(ListNode head, ListNode tobeDelete) { if (head == null || tobeDelete == null) { return null; } if (tobeDelete.next != null) { // 要删除的节点不是尾结点 ListNode next = tobeDelete.next; tobeDelete.val = next.val; tobeDelete.next = next.next; } else { if (head == tobeDelete) { // 只有一个节点 head = null; } else { ListNode cur = head; while (cur.next != tobeDelete) { cur = cur.next; } cur.next = null; } } return head; } public static void main(String[] args) { } }
【每日寄语】 窦燕山,有义方;教五子,名俱扬。
Recommend
-
20
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。 返回删除后的链表的头节点。 注意:此题对比原题有改动 示例 1: 输入: head = [4,5,1,9], val = 5 ...
-
8
What is your Identity? Devchat.tv Devchat.tv What is your Identity? - .NET 069...
-
6
LeetCode 图解 | 19.删除链表的倒数第N个节点-程序员小吴 当前位置:程序员小吴 > LeetCodeAnimation > LeetCode 图解 | 19.删除链表的倒数第N...
-
11
LeetCode 第 19 号问题:删除链表的倒数第 N 个节点-程序员小吴 当前位置:程序员小吴 > LeetCodeAnimation > LeetCode 第 19 号问题:删除链表...
-
4
LeetCode-069-x的平方根发布于 59 分钟前x 的平方根题目描述:实现 int sqrt(int x) 函数。计算并返回 x 的平方根,其中 x 是非负整数...
-
8
Newegg上半年营收12.069亿美元!同比增长39.9%!-跨境头条-AMZ123亚马逊导航-跨境电商出海门户 Newegg上半年营收12.069亿美元!同比增长39.9%!...
-
6
详解双向循环带头节点链表——十分钟单手吊打链表 推荐 原创 知晓天空之蓝 2022-03-24 18:00...
-
8
玩转内核链表Llist_Head,教你管理不同类型节点的实现 作者:土豆居士 2022-09-15 11:51:28 虽然Linux内核是用C语言写的,但是list_head的引入,使得内核数据结构也可以拥有面向对象的特性,通过使用操作list_head...
-
6
Daily Wrap Up – April 17, 2023 (#069) There’s very little commonality to what I read today, but this is what you come here for, right? RIGHT? Check out some good content on platform enginee...
-
4
Breadcrumbs/069-coq-roadmap.md...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK