当前位置:网站首页>18.删除链表的倒数第n个节点
18.删除链表的倒数第n个节点
2022-07-26 02:13:00 【linsa_pursuer】
给定一个链表,删除链表的倒数第 n 个节点并返回链表的头指针
例如,
给出的链表为: 1\to 2\to 3\to 4\to 51→2→3→4→5, n= 2n=2.
删除了链表的倒数第 nn 个节点之后,链表变为1\to 2\to 3\to 51→2→3→5.
数据范围: 链表长度 0\le n \le 10000≤n≤1000,链表中任意节点的值满足 0 \le val \le 1000≤val≤100
要求:空间复杂度 O(1)O(1),时间复杂度 O(n)O(n)
备注:
题目保证 nn 一定是有效的
示例1
输入:
{1,2},2
复制
返回值:
{2}
代码如下:
import lombok.ToString;
@ToString
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}public class Main {
public static void main(String[] args) throws Exception {
ListNode head = new ListNode(1);
ListNode headOne = new ListNode(2);
ListNode headTwo = new ListNode(3);
head.next = headOne;
headOne.next = headTwo;
System.out.println(head);
System.out.println(removeNthFromEnd(head, 3));
}
public static ListNode removeNthFromEnd (ListNode head, int n) {
ListNode first = head;
ListNode second = head;
for(int i = 0; i < n; i++) {
first = first.next;
}
//如果n的值等于链表的长度,直接返回去掉头结点的链表
if (first == null) {
return head.next;
}
while(first.next != null) { //同时移动两个指针
first = first.next;
second = second.next;
}
second.next = second.next.next;
return head;
}
}边栏推荐
- 1. Mx6ul core module serial use - touch screen calibration (IX)
- AttributeError: ‘Document‘ object has no attribute ‘pageCount‘
- [2021] [paper notes] 6G technology vision - otfs modulation technology
- mysql 事务隔离级别
- SQLyog数据导入导出图文教程
- Video game quiz? I think it's useless. It's better to do these well!
- prometheus+blackbox-exporter+grafana 监控服务器端口及url地址
- Qt程序美化之样式表的使用方法,Qt使用图片作为背景与控件透明化,Qt自定义按钮样式
- 【红队】ATT&CK - 利用BITS服务实现持久化
- [C language brush leetcode] 735. Planetary collision (m)
猜你喜欢

主键B+ Tree,二级索引B+ Tree及对应的查询过程分析

I.MX6UL核心模块使用连载-查看系统信息 (二)

1. Mx6ul core module uses serial can and buzzer test (XI)

Characteristics and determination of neuraminidase from Clostridium perfringens in Worthington

1. Mx6ul core module serial WiFi test (VIII)

C# 迭代器的实现

SQL手工盲注、报错注入

Error reporting caused by local warehouse

I came to the library applet one click sign in and one click grab location tool

由一个数据增量处理问题看到技术人员的意识差距
随机推荐
【2019】【论文笔记】基于超材料可调谐THz宽频吸收——
mysql 事务隔离级别
TCP三次握手四次挥手
1205 Lock wait timeout exceeded; Try restarting transaction processing
图解B+树的插入过程
[2021] [paper notes] biological effects of cell membrane under infrared and THz - effect is a phenomenon, action is a mechanism - the benefits of THz to medicine
C# 迭代器的实现
Obsidian mobile PC segment synchronization
19_请求表单与文件
1. Mx6ul core module uses serial can and buzzer test (XI)
ggplot2学习总结
i.MX6ULL SNVS电源域GPIO状态保持验证
js给页面添加随机像素噪声背景
1. Mx6ul core module serial WiFi test (VIII)
Redis6.x配置参数详解
1. Mx6ul core module serial Ethernet test (VII)
prometheus+blackbox-exporter+grafana 监控服务器端口及url地址
Navica工具把远程MySQL导入到本地MySQL数据库
Monitoring of debezium synchronization debezium
I.MX6UL核心模块使用连载-WIFI测试 (八)