当前位置:网站首页>LeetCode 热题 HOT 100(10.删除链表的倒数第 N 个结点)
LeetCode 热题 HOT 100(10.删除链表的倒数第 N 个结点)
2022-08-07 14:38:00 【识时务者-HJJ】
10.删除链表的倒数第 N 个结点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:

输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
提示:
链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
package com.leetcode;
import java.util.ArrayList;
import java.util.List;
/** * @Author Handsome * @Date 2022/8/6 20:17 * @Version 1.0 */
public class 删除链表的倒数第N个结点 {
/** * Definition for singly-linked list. */
public static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static void main(String[] args) {
ListNode listNode = removeNthFromEnd(
new ListNode(1,
new ListNode(2,
new ListNode(3,
new ListNode(4,
new ListNode(5))))), 2);
List list = new ArrayList();
while (listNode != null) {
list.add(listNode.val);
listNode = listNode.next;
}
System.out.println(list);
// 输出结果 [1, 2, 3, 5]
}
/** * 双指针 * 复杂度分析: * 时间复杂度:O(L),其中 L 是链表的长度。 * 空间复杂度:O(1)。 */
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode first = head;
ListNode second = dummy;
for (int i = 0; i < n; ++i) {
first = first.next;
}
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
ListNode ans = dummy.next;
return ans;
}
}
我的学习论坛
HandsomeForum:用Java编写的学习论坛,打造我们自己的圈子!(http://huangjunjie.vip:66)
边栏推荐
- 【vscode代码片段增加和删除】
- 004_Eureka注册中心
- Lianshengde W801 series 4-MQTT use
- C专家编程 第8章 为什么程序员无法分清万圣节和圣诞节 8.3 在等待时类型发生了变化
- Expert C Programming Chapter 8 Why Programmers Can't Tell the Difference Between Halloween and Christmas 8.2 Building Graphics from Bit Patterns
- 联盛德W801系列1-flash保存数据例程:保存wifi配网信息
- 一个程序从编译到运行的全过程
- [YOLOv7_0.1] Network structure and source code analysis
- C Expert Programming Chapter 8 Why Programmers Can't Tell the Difference Between Halloween and Christmas 8.7 Implementing Finite State Machines in C
- How about Qiniu's CITIC Securities VIP commission account?Is it safe and reliable?
猜你喜欢
随机推荐
Is it safe to use Tongdaxin software to buy stocks?
HJ6 prime factor
桥接模式:Swift 实现
哈希表 | 1. 两数之和、454. 四数相加 | 用`字典key-value`最合适 | leecode刷题笔记
注销/撤销/吊销
使用通达信软件买股票安全吗?
HJ6 质数因子
@RequestMapping注解标识的位置
内存管理(五)——内存回收
dotnet 获取本机 IP 地址方法
MethodInterceptor
How a Phase Locked Loop Works
雷达的分辨率
做一个物联网云平台到底要多少钱?
关于云和恩墨对“HTAP”和“智能仓湖”等关系的研究
联盛德W801系列2-WIFI一键配网,信息保存
1403. 非递增顺序的最小子序列
win10 uwp iot
001_微服务框架学习分类总结
MySQL: Calculate shortest distance between latitude and longitude using custom function





![[Leetcode]21. 合并两个有序链表](/img/86/e3a14a64dafece194e44aec91cea44.png)


