当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢

Redis persistence method

Go编译原理系列7(Go源码调试)

Code Casual Recording Notes_Dynamic Programming_416 Segmentation and Subsetting

小身材有大作用——光模块基础知识(一)

RSS订阅微信公众号初探-feed43

(PC+WAP)织梦模板螺钉手柄类网站

Prometheus监控Harbor(二进制版)

The super perfect layout has shortcut keys and background replacement

(PC+WAP)织梦模板不锈钢类网站

【杂项】如何将指定字体装入电脑然后能在Office软件里使用该字体?
随机推荐
Pytest学习-skip/skipif
V8中的快慢数组(附源码、图文更易理解)
射频芯片(RFIC)的协议之5G及其调制
[2022安恒夏令营] 5个小题
Internship: Upload method for writing excel sheet (import)
禾匠编译错误记录
Super perfect version of the layout have shortcut, background replacement (solve the problem of opencv Chinese path)
七夕活动浪漫上线,别让网络拖慢和小姐姐的开黑时间
2021年数据泄露成本报告解读
Free自由协议系统开发
redis持久化方式
The salary of soft testers at each stage, come to Kangkang, how much can you get?
超级完美版布局有快捷键,有背景置换(解决opencv 中文路径问题)
Why Flutter Flutter of tutorials is the best choice for business?
Pytest learn-setup/teardown
智能座舱的「交互设计」大战
Code Casual Recording Notes_Dynamic Programming_416 Segmentation and Subsetting
The curl using guide
单例模式使用饿汉式和懒汉式创建一定安全?很多人不知
Flutter教程之为什么 Flutter 是创业的最佳选择?