当前位置:网站首页>剑指 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;
}
}
边栏推荐
- 'resultmap'must match' (constructor?, id*, result*, association*, collect problem solving
- [machine learning basics] - another perspective to explain SVM
- Talk about C pointer
- Causes and solutions of QT signal and slot connection failure
- 期盼已久全平台支持-开源IM项目OpenIM之uniapp更新
- 1184. 公交站间的距离
- OpenMP入门
- By default, the select drop-down box selects the solution ligerui that the selected attribute does not work
- Qualcomm reconciled with apple and received at least $4.5 billion in settlement fees! Next goal: Huawei!
- TCP协议调试工具TcpEngine V1.3.0使用教程
猜你喜欢

15、ARM嵌入式系统:如何用PC调试单板
![[Nanjing Agricultural University] information sharing of postgraduate entrance examination and re examination](/img/1d/550a991385b842a21e2b301725407e.png)
[Nanjing Agricultural University] information sharing of postgraduate entrance examination and re examination

简单使用 MySQL 索引

Template method mode

PS pull out logo

15. ARM embedded system: how to debug single board with PC

多线程(基础)

Mcd12q1 data shows multiple classifications in envi

Telephone system rules

Talk about C pointer
随机推荐
ArcGIS layer annotation display
ARP 入门
Due to lack of funds, Changdian technology sold some assets of Xingke Jinpeng for 120million US dollars!
[leetcode] day103 search two-dimensional matrix II
leetcode:162. 寻找峰值【二分寻找峰值】
EMQ Yingyun technology was listed on the 2022 "cutting edge 100" list of Chinese entrepreneurs
Multithreading (basic)
MySQL converts strings to numeric types and sorts them
Wentai technology and Baoxin software deepened 5g cooperation, and 5g manufacturing settled in Baowu, China
[leetcode] skillfully use bit operation
城市安全系列科普丨进入溺水高发期,救生常识话你知
MySQL write lock does not take effect
With regard to performance testing, dry goods hit "suggestions collection"
2019q1 global smartphone shipments: Huawei vivo increased significantly, while Apple plummeted 30.2%!
1184. Distance between bus stops
1163: 松哥的分数拆分(C语言)
[leetcode]38. counting - problem solving (execution time beat 91%, memory consumption beat 97%)
Using native JS to realize magnifying glass function
简易版QQ?Qt也可以实现!(一)
Mobile phone comparison redmi note8 and realm x2