Leetcode 237:Delete Node in a Linked List
2021/7/11 11:08:02
本文主要是介绍Leetcode 237:Delete Node in a Linked List,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Leetcode 237:Delete Node in a Linked List
Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.
It is guaranteed that the node to be deleted is not a tail node in the list.
说人话:
单链表中结点不重复,给你一个结点,删除掉这个结点。
要点:
- 没有给头结点,只给了要删除的那个结点
- 结点不重复
- 链表至少包含两个节点
- 给定的节点为非末尾节点并且一定是链表中的一个有效节点
示例:
![image-20210206110329090](/upload/202107/11/202107111108016025.png)
[法1] 修改结点的值
思路
因为本题没有给我们 head 结点,所以我们不可能得到要删除的结点 node 的前一个结点 pre,所以是不可能删除掉 node 结点本身的。
我们可以利用结点唯一
这个条件,将要删除的结点 node 后面的结点 next 的值覆盖到 node 上面,然后删除掉 next 直接,就等价于删除掉 node 结点。
代码
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public void deleteNode(ListNode node) { ListNode next = node.next; node.val = next.val; node.next = next.next; } }
提交结果
![image-20210206110710320](/upload/202107/11/202107111108019804.png)
代码分析
- 时间复杂度:O(1)
- 空间复杂度:O(1)
这篇关于Leetcode 237:Delete Node in a Linked List的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-06Package Easy(基于 NSIS 的打包exe安装包工具)使用方法-icode9专业技术文章分享
- 2024-06-06基于 casdoor 的 ELK 开源登录认证解决方案: elk-auth-casdoor-icode9专业技术文章分享
- 2024-05-29Elasticsearch慢查询日志配置
- 2024-05-29揭秘华为如此多成功项目的产品关键——Charter模板
- 2024-05-29海外IDC业务拓展的7大挑战
- 2024-05-29InLine Chat功能优化对标Github Copilot,CodeGeeX带来更高效、更直观的编程体验!
- 2024-05-29CodeGeeX 智能编程助手 6 项功能升级,在Visual Studio插件市场霸榜2周!
- 2024-05-29AutoMQ 生态集成 Apache Doris
- 2024-05-292024年IDC行业的深度挖掘:机遇、挑战与未来展望
- 2024-05-29五款扩展组件齐发 —— Volcano、Keda、Crane-scheduler 等,邀你体验