当前位置:网站首页>剑指 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
边栏推荐
- Input file upload
- Simulation of infrared wireless communication based on 51 single chip microcomputer
- Learning record of uni app dark horse yougou project (Part 2)
- PC电脑使用无线网卡连接上手机热点,为什么不能上网
- Shell - introduction, variables, and basic syntax
- [batch change MySQL table and corresponding codes of fields in the table]
- 1-3 nodejs installation list configuration and project environment
- Come out after a thousand calls
- HCIP第五次实验
- Shell-入门、变量、以及基本的语法
猜你喜欢
Using quartz under. Net core - [1] quick start
双闭环直流调速系统matlab/simulink仿真
Using quartz under. Net core -- job attributes and exceptions of [4] jobs and triggers
Future 用法详解
Further study of data visualization
Simulation of infrared wireless communication based on 51 single chip microcomputer
Signalr can actively send data from the server to the client
Use between nodejs modules
为什么有些人说单片机简单,我学起来这么吃力?
Scope and scope chain in JS
随机推荐
Excel quickly and automatically fills the contents of a row on a blank cell
Allowed latency and side output
Solution of Navicat connecting Oracle library is not loaded
Use of five routing guards
Using quartz under. Net core -- general properties and priority of triggers for [5] jobs and triggers
Promise (IV)
Baidu Map Case - Zoom component, map scale component
2. Electron's HelloWorld
El cascade and El select click elsewhere to make the drop-down box disappear
线性代数感悟之1
ASP. Net core reads the configuration file in the class library project
How to manually implement the mechanism of triggering garbage collection in node
[ES6] promise related (event loop, macro / micro task, promise, await / await)
Summary of common websites
Shell-cut命令的使用
常用SQL语句总结
How does matlab draw the curve of known formula and how does excel draw the function curve image?
练习:求偶数和、阈值分割和求差( list 对象的两个基础小题)
. net type transfer
Open futures, open an account, cloud security or trust the software of futures companies?