当前位置:网站首页>剑指 Offer 22. 链表中倒数第k个节点-快慢指针
剑指 Offer 22. 链表中倒数第k个节点-快慢指针
2022-04-23 17:32:00 【hequnwang10】
一、题目描述
输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。
例如,一个链表有 6 个节点,从头节点开始,它们的值依次是 1、2、3、4、5、6。这个链表的倒数第 3 个节点是值为 4 的节点。
示例 1:
给定一个链表: 1->2->3->4->5, 和 k = 2.
返回链表 4->5.
二、解题
快慢指针
快慢指针相差K个节点,然后更新快慢指针
/** * 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) {
//快慢指针
if(head == null){
return head;
}
ListNode fast = head;
ListNode slow = head;
for(int i = 0;i<k;i++){
fast = fast.next;
}
while(fast != null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
版权声明
本文为[hequnwang10]所创,转载请带上原文链接,感谢
https://blog.csdn.net/hequnwang10/article/details/124333889
边栏推荐
- Clickhouse - data type
- Tdan over half
- Why do some people say SCM is simple and I have to learn it so hard?
- The system cannot be started after AHCI is enabled
- 线性代数感悟之1
- Promise (II)
- Come out after a thousand calls
- In ancient Egypt and Greece, what base system was used in mathematics
- [related to zhengheyuan cutting tools]
- 开期货,开户云安全还是相信期货公司的软件?
猜你喜欢
uni-app黑马优购项目学习记录(下)
Using quartz under. Net core -- general properties and priority of triggers for [5] jobs and triggers
[WPF binding 3] listview basic binding and data template binding
SiteServer CMS5. 0 Usage Summary
[ES6] promise related (event loop, macro / micro task, promise, await / await)
双闭环直流调速系统matlab/simulink仿真
2.Electron之HelloWorld
.Net Core3. 1 use razorengine NETCORE production entity generator (MVC web version)
PC uses wireless network card to connect to mobile phone hotspot. Why can't you surf the Internet
Tdan over half
随机推荐
stm32入门开发板选野火还是正点原子呢?
In ancient Egypt and Greece, what base system was used in mathematics
Seven cattle upload pictures (foreground JS + background C API get token)
Devexpress GridView add select all columns
For the space occupation of the software, please refer to the installation directory
Use of todesk remote control software
Model problems of stock in and stock out and inventory system
【WPF绑定3】 ListView基础绑定和数据模板绑定
Tdan over half
Using quartz under. Net core - calendar of [6] jobs and triggers
C语言程序设计之函数的构造
[logical fallacy in life] Scarecrow fallacy and inability to refute are not proof
node中,如何手动实现触发垃圾回收机制
The system cannot be started after AHCI is enabled
Oninput one function to control multiple oninputs (take the contents of this input box as parameters) [very practical, very practical]
uni-app黑马优购项目学习记录(下)
EF core in ASP Generate core priority database based on net entity model
Using quartz under. Net core - [1] quick start
Clickhouse - data type
【生活中的逻辑谬误】稻草人谬误和无力反驳不算证明