当前位置:网站首页>链表相关方法
链表相关方法
2022-07-26 00:03:00 【林纾໌້ᮨ】
1.链表中倒数第k个结点_牛客网
思路:快慢指针
快指针先走k步,慢指针再和快指针一块走,当快指针走到null时慢指针就刚好走到倒数第k个结点位置
public ListNode FindKthToTail(ListNode head,int k) {
if(k<=0||head==null){
return null;
}
ListNode fast=head;
ListNode slow=head;
// for(int i=0;i<k;i++){
// fast=fast.next;
//}
while(k>0&&fast!=null){
fast=fast.next;
k--;
}
//理论上这里应判断一次k值是否满足条件,但此处直接先判断fast了
//这里要注意k>0且fast==null情况:eg:1->2->3,求倒数第5个结点,此时fast遍历到最后为空但k仍旧大于0
//进入下面循环时k一定是等于0的,如果k>0但是fast为空就无法进入循环
//慢指针在头部,快慢指针之间相差k,让他们一块走
while(fast!=null){
fast=fast.next;
slow=slow.next;
}
return k>0?null:slow;
}这里注意要时刻注意k的正确性,当k<0时不满足条件,无效,返回null,当k超过链表长度也是不满足条件的,k超过长度时的判断可以加到到快指针前移处一起判断,当k>0&&fast!=null时移动指针,出循环时指针要么是k==0了,此时属于正常情况走了k步,直接移动快慢指针找对应位置即可,另一种情况就是k仍旧大于0但是fast走到null了,此时说明k的次数比链表元素个数多,也是无效的,直接返回null即可。
2.反转链表_牛客网
边栏推荐
- MySQL——主从复制
- SIGIR '22 recommendation system paper graph network
- Dead letter queue and message TTL expiration code
- Binary tree - 617. Merge binary tree
- LeetCode高频题66. 加一,给你一个数组表示数字,则加1返回结果
- 栈与队列——239. 滑动窗口最大值
- The items of listview will be displayed completely after expansion
- 行为型模式之观察者模式
- Article 75: writing skills of academic papers
- Backtracking - 17. Letter combinations of phone numbers
猜你喜欢

Compile live555 with vs2019 in win10

Lua脚本编写Wireshark插件解析第三方私有协议

本轮牛市还能持续多久?|疑问解答 2021-05-11

NVIDIA cudnn learning

Part 74: overview of machine learning optimization methods and superparameter settings

痞子衡嵌入式:MCUXpresso IDE下将源码制作成Lib库方法及其与IAR,MDK差异

牛市还将继续,拿好手里的币 2021-05-08

Observer model of behavioral model

Js理解之路:写一个比较完美的组合继承(ES5)

如何用yolov5 做个闯红灯监控的智能交通系统(1)
随机推荐
MySQL——数据库日志
Find the intermediate node of the linked list
注解@Autowired源码解析
Stack and queue - 239. Sliding window maximum
Binary tree - 404. Sum of left leaves
SQLZOO——Nobel Quiz
Solve the problem of rapid index bar extrusion
@The underlying principle of Autowired annotation
牛市还将继续,拿好手里的币 2021-05-08
如何用yolov5 做个闯红灯监控的智能交通系统(1)
Observer model of behavioral model
回溯——77. 组合
寻找链表的中间节点
NVIDIA可编程推理加速器TensorRT学习笔记(三)——加速推理
Getaverse,走向Web3的远方桥梁
Module II operation
二叉树——654. 最大二叉树
07_ue4进阶_发射火球扣mp值和攻击扣血机制
GUI interface of yolov3 (2) -- beautify the page + output the name and quantity of the identified object
Backtracking - 17. Letter combinations of phone numbers