当前位置:网站首页>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;
}
}
边栏推荐
- 【LeetCode】最长回文子序列(动态规划)
- ts用法大全
- The longest substring that cannot have repeating characters in a leetcode/substring
- 2022/8/3 Exam Summary
- RSS feeds WeChat public - feed43 asain
- 七夕活动浪漫上线,别让网络拖慢和小姐姐的开黑时间
- Deep integration of OPC UA and IEC61499 (1)
- 跨域的学习
- 雅思大作文写作模版
- 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
猜你喜欢
随机推荐
一文搞定 SQL Server 执行计划
图论-虚拟节点分层建图
【MySQL —— 索引】
Internship: Upload method for writing excel sheet (import)
Three.js入门详解
Creo 9.0在草图环境中创建坐标系
Jmeter-断言
超级完美版布局有快捷键,有背景置换(解决opencv 中文路径问题)
【杂项】如何将指定字体装入电脑然后能在Office软件里使用该字体?
雅思大作文写作模版
Pytest learn-setup/teardown
Super perfect version of the layout have shortcut, background replacement (solve the problem of opencv Chinese path)
XSLT – 服务器端概述
Creo 9.0二维草图的诊断:加亮开放端点
Zilliz 2023 Fall Campus Recruitment Officially Launched!
最小化安装debian11
简单了解下 TCP,学习握手和挥手以及各种状态到底是怎么样的
End-to-End Lane Marker Detection via Row-wise Classification
The longest substring that cannot have repeating characters in a leetcode/substring
V8中的快慢数组(附源码、图文更易理解)









