当前位置:网站首页>剑指 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
边栏推荐
- Using quartz under. Net core -- operation transfer parameters of [3] operation and trigger
- ECMAScript history
- ASP. Net core JWT certification
- JS, entries(), keys(), values(), some(), object Assign() traversal array usage
- Using quartz under. Net core -- job attributes and exceptions of [4] jobs and triggers
- Baidu Map 3D rotation and tilt angle adjustment
- Input file upload
- [ES6] promise related (event loop, macro / micro task, promise, await / await)
- MySQL installation
- 1-5 nodejs commonjs specification
猜你喜欢
Net standard
【生活中的逻辑谬误】稻草人谬误和无力反驳不算证明
flink 学习(十二)Allowed Lateness和 Side Output
ASP. Net core dependency injection service life cycle
QT modification UI does not take effect
双闭环直流调速系统matlab/simulink仿真
EF core in ASP Generate core priority database based on net entity model
stm32入门开发板选野火还是正点原子呢?
超分之TDAN
HCIP第五次实验
随机推荐
How does matlab draw the curve of known formula and how does excel draw the function curve image?
Shell-sort命令的使用
Open futures, open an account, cloud security or trust the software of futures companies?
.Net Core3. 1 use razorengine NETCORE production entity generator (MVC web version)
ECMAScript history
Manually implement simple promise and its basic functions
Use between nodejs modules
PC uses wireless network card to connect to mobile phone hotspot. Why can't you surf the Internet
Summary of common websites
2.Electron之HelloWorld
嵌入式系统中,FLASH中的程序代码必须搬到RAM中运行吗?
Using quartz under. Net core -- a simple trigger of [7] operation and trigger
Signalr can actively send data from the server to the client
JS to find the character that appears three times in the string
Low code development platform sorting
How to use the input table one-way service to send (occupy less) picture files (body transmission)? FileReader built-in object involved
ASP. NET CORE3. 1. Solution to login failure after identity registers users
Clickhouse table engine
Deep understanding of control inversion and dependency injection
双指针进阶--leetcode题目--盛最多水的容器