当前位置:网站首页>剑指 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
边栏推荐
- 给 el-dialog 增加拖拽功能
- Clickhouse table engine
- [PROJECT] small hat takeout (8)
- Exercise: even sum, threshold segmentation and difference (two basic questions of list object)
- Advantages and disadvantages of several note taking software
- Router object, route object, declarative navigation, programmed navigation
- Simulation of infrared wireless communication based on 51 single chip microcomputer
- How to change input into text
- .Net Core3. 1 use razorengine NETCORE production entity generator (MVC web version)
- matlab如何绘制已知公式的曲线图,Excel怎么绘制函数曲线图像?
猜你喜欢
ASP. NET CORE3. 1. Solution to login failure after identity registers users
PC电脑使用无线网卡连接上手机热点,为什么不能上网
Deep understanding of control inversion and dependency injection
Collection of common SQL statements
STM32 entry development board choose wildfire or punctual atom?
Use of five routing guards
How to change input into text
In embedded system, must the program code in flash be moved to ram to run?
快时钟同步慢时钟域下的异步控制信号slow clk to fast clk
Use of todesk remote control software
随机推荐
Understanding and small examples of unity3d object pool
HCIP第五次实验
Understanding of RPC core concepts
练习:求偶数和、阈值分割和求差( list 对象的两个基础小题)
Entity Framework core captures database changes
Come out after a thousand calls
Use of shell cut command
freeCodeCamp----prob_ Calculator exercise
JS to find the character that appears three times in the string
Use between nodejs modules
Clickhouse SQL operation
Websocket (basic)
1-2 characteristics of nodejs
ASP. NET CORE3. 1. Solution to login failure after identity registers users
Deep understanding of control inversion and dependency injection
In ancient Egypt and Greece, what base system was used in mathematics
Learning record of uni app dark horse yougou project (Part 2)
Some problems encountered in recent programming 2021 / 9 / 8
Summary of common SQL statements
ASP. Net core dependency injection service life cycle