当前位置:网站首页>剑指 Offer 22. 链表中倒数第k个节点
剑指 Offer 22. 链表中倒数第k个节点
2022-07-24 16:31:00 【ThE wAlkIng D】
题目描述

问题解析
使用快慢指针双指针来做,倒数第K的意思就是快慢指针相隔k个单位进行遍历
首先先让快指针走K个单位,while循环遍历快指针
接着再让慢指针和快指针一起向后走,在并列一个while循环,走快慢指针。
(链表的题目多是使用while循环)
代码实例
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode fast = head;
ListNode slow = head;
while(fast != null&& k > 0){
fast = fast.next;
k--;
}
while(fast != null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
边栏推荐
- Creation and inheritance of JS class
- C# TCP客户端窗体应用程序异步接收方式
- Use of ec200u-cn module
- Four common post submission methods (application / x-www-form-urlencoded, multipart / form data, application / JSON, text / XML)
- How to realize seamless rotation map? Write it again with native JS
- Solve the timeliness problem caused by Eureka's default cache configuration
- Huawei Kirin 985 mass production in the third quarter: TSMC 7Nm EUV process, integrated 5g baseband!
- [technology] online seat selection demo of uniapp
- Software recommendation - Mechanical Major
- 【技术】uniapp 之 在线选座 demo
猜你喜欢

EMQ Yingyun technology was listed on the 2022 "cutting edge 100" list of Chinese entrepreneurs

期盼已久全平台支持-开源IM项目OpenIM之uniapp更新

After data management, the quality is still poor

Mobile phone comparison redmi note8 and realm x2

Jupyter uses tips

PS pull out logo

MODIS data WGet Download

287 finding duplicates

Envi grid resampling

Rest style
随机推荐
栈与队列——1047. 删除字符串中的所有相邻重复项
Wentai technology and Baoxin software deepened 5g cooperation, and 5g manufacturing settled in Baowu, China
Four common post submission methods (application / x-www-form-urlencoded, multipart / form data, application / JSON, text / XML)
With notes: printing order of synchronous, asynchronous, micro task and macro task
Ligerui table control grid changes the color of rows (cells) according to the content
Creation and inheritance of JS class
城市安全系列科普丨进入溺水高发期,救生常识话你知
What is the difference between cookies, localstorage and sessionstorage?
Traverse, delete, judge whether JSON data is empty, and recursion
deepin任务栏消失解决方法
With regard to performance testing, dry goods hit "suggestions collection"
QT keyboard event (II) -- long press the key to trigger the event event repeatedly, and the problem is solved
安全的证券公司有哪些?我想在手机上买股票
'resultmap'must match' (constructor?, id*, result*, association*, collect problem solving
如何防止跨站点脚本 (XSS) 攻击完整指南
Jupyter uses tips
Stack and queue - 1047. Delete all adjacent duplicates in the string
Mcd12q1 data shows multiple classifications in envi
简易版QQ?Qt也可以实现!(一)
Software recommendation - Mechanical Major