当前位置:网站首页>LeetCode 19:删除链表的倒数第 N 个结点
LeetCode 19:删除链表的倒数第 N 个结点
2022-08-03 23:50:00 【斯沃福德】
题目:
方法一:双指针
如果要删除倒数第n个节点,让fast移动n步,目的是拉开fast和slow之间的距离;
然后让fast和slow同时移动,直到fast指向链表末尾,此时slow就是要删除的节点!
最后fast为末尾节点的next即为null,slow就是要删除的节点node,而pre节点记录了node的前节点!
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(n<=0){
return head;
}
// 哨兵节点!
ListNode mer=new ListNode(-1);
mer.next=head;
ListNode fast=mer;
ListNode slow=mer;
//fast移动n次
for(int i=0;i<n;i++){
fast=fast.next;
}
ListNode pre=null;
while(fast!=null){
pre=slow;
// slow和fast一起移动,直到fast到末尾
slow=slow.next;
fast=fast.next;
}
// 删除
pre.next=slow.next;
return mer.next;
}
}
方法二:模拟
直接按情况分类计算;
排除k>size和k=size=1的特殊情况;
如果k=1且size>1,即删除最后一个节点;
如果k>1且k=size,即删除第一个,那么直接返回第二个节点即可;
而k>1且k<size时,将前驱节点指向要删除节点的next即完成删除;
class Solution {
public ListNode removeNthFromEnd(ListNode head, int k) {
Stack<ListNode> s=new Stack<>();
ListNode curr=head;
while(curr!=null){
s.push(curr);
curr=curr.next;
}
// base case
if(k>s.size() || k<=0){
return head;
}
if(k==1 && s.size()==1){
return null;
}
else if(k==1 && s.size()>1 ){
s.pop();
ListNode pre=s.pop();
pre.next=null;
}else if(k>1 && k==s.size()){
ListNode second=null;
for(int i=0;i<k-1;i++){
second=s.pop();
}
return second;
}else if(k>1 && k<s.size()){
ListNode front=null;
for(int i=0;i<k+1;i++){
front=s.pop(); // 前
}
front.next=front.next.next;
}
return head;
}
}
边栏推荐
- 响应式织梦模板除尘器类网站
- - the skip/skipif Pytest learning
- 【LeetCode】最长回文子序列(动态规划)
- redis持久化方式
- 设置工作模式与环境(下):探查和收集信息
- libnet
- Create function report error, prompting DECLARE definition syntax problem
- The longest substring that cannot have repeating characters in a leetcode/substring
- Zilliz 2023 Fall Campus Recruitment Officially Launched!
- RSS订阅微信公众号初探-feed43
猜你喜欢
随机推荐
现货白银需要注意八大事项
Fluorescein-PEG-CLS, cholesterol-polyethylene glycol-fluorescein scientific research reagent
689. 三个无重叠子数组的最大和
In V8 how arrays (with source code, picture and text easier to understand)
超级完美版布局有快捷键,有背景置换
sqlnet.ora文件与连接认证方式的小测试
Minimized installation of debian11
Creo 9.0二维草图的诊断:加亮开放端点
用队列模拟实现栈
Unity2021 releases WebGL fog effect disappearing problem
Unity intercepts 3D images and the implementation of picture-in-picture PIP
Shell编程之循环语句与函数
internship:编写excel表的上传方法(导入)
Interpretation of ML: A case of global interpretation/local interpretation of EBC model interpretability based on titanic titanic rescued binary prediction data set using interpret
curl使用指南
rsync 基础用法
禾匠编译错误记录
一文搞定 SQL Server 执行计划
3D Semantic Segmentation - 2DPASS
Unity 截取3D图像 与 画中画PIP的实现