当前位置:网站首页>剑指 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
边栏推荐
- Seven cattle upload pictures (foreground JS + background C API get token)
- Excel quickly and automatically fills the contents of a row on a blank cell
- Clickhouse - data type
- If you start from zero according to the frame
- ECMAScript history
- Use of todesk remote control software
- stm32入门开发板选野火还是正点原子呢?
- Learning record of uni app dark horse yougou project (Part 2)
- [related to zhengheyuan cutting tools]
- Shell-入门、变量、以及基本的语法
猜你喜欢

uni-app黑马优购项目学习记录(下)

Clickhouse table engine
![Using quartz under. Net core -- job attributes and exceptions of [4] jobs and triggers](/img/ec/43dddd18f0ce215f0f1a781e31f6a8.png)
Using quartz under. Net core -- job attributes and exceptions of [4] jobs and triggers
![[logical fallacy in life] Scarecrow fallacy and inability to refute are not proof](/img/71/14a17128dbe0f02edb4db3da479ef2.jpg)
[logical fallacy in life] Scarecrow fallacy and inability to refute are not proof

Summary of common SQL statements

Tdan over half

嵌入式系统中,FLASH中的程序代码必须搬到RAM中运行吗?

Understanding of RPC core concepts

Use between nodejs modules

Qt 修改UI没有生效
随机推荐
Excel quickly and automatically fills the contents of a row on a blank cell
ASP. NET CORE3. 1. Solution to login failure after identity registers users
Tdan over half
读《Software Engineering at Google》(15)
[C#] 彻底搞明白深拷贝
JVM类加载机制
ASP. Net core configuration options (Part 2)
Shell-入门、变量、以及基本的语法
Some problems encountered in recent programming 2021 / 9 / 8
Preliminary understanding of promse
JS, entries(), keys(), values(), some(), object Assign() traversal array usage
How to use the input table one-way service to send (occupy less) picture files (body transmission)? FileReader built-in object involved
Promise (IV)
El cascade and El select click elsewhere to make the drop-down box disappear
[simple understanding of database]
If you start from zero according to the frame
Promise (I)
Learning record of uni app dark horse yougou project (Part 2)
Why do some people say SCM is simple and I have to learn it so hard?
Shell-awk命令的使用