当前位置:网站首页>【剑指Offer】22.链表中倒数第K节点
【剑指Offer】22.链表中倒数第K节点
2022-06-11 16:00:00 【LuZhouShiLi】
剑指Offer 22.链表中倒数第K节点
题目

思路
- 初始化一个前指针former和一个后指针latter,两个指针都指向头节点head
- 前指针先向前走K步,(结束之后,双指针former和latter间相距k步)
- 之后两个指针同时进行移动,former和latter都向前走一步,直到former指向空,那们此时Latter和尾节点相差k - 1步,也就是指向倒数第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) {
ListNode former = head;
ListNode latter = head;
// 第一个指针先走k步
for(int i = 0; i < k; i++)
{
if(former == null)
{
return null;
}
former = former.next;
}
// 那么第一个指针与第二个指针相差k步 因为此时第一个指针former在 k + 1位置 latter还在第一个位置
// 当第一个指针跳出之后 former指向空 那么latter和former相差k步,那们也就是和尾部节点相差k - 1步
while(former != null)
{
// 将第一个指针移动到链表尾部
former = former.next;
latter = latter.next;
}
return latter;
}
}
边栏推荐
- PyQt5 使QPlainTextEdit控件支持行号显示
- Golang map basic operations
- The difference between go language array and slice
- 无心剑英汉双语诗001. 《春游》
- Data enhancement
- What happened to the frequent disconnection of the computer at home
- GO語言-值類型和引用類型
- Laravel8 implementation of sign in function
- PostgreSQL create database
- 用户界面之工具栏详解-AutoRunner自动化测试工具
猜你喜欢

泰雷兹云安全报告显示,云端数据泄露和复杂程度呈上升趋势

Go language slice

DHCP协议实例化分析

Take you in-depth understanding of AGC cloud database

Opengauss version 3.0.0 was officially released, and immediately experience the first lightweight version in the community

Open the door of the hybrid cloud market, Lenovo xcloud's way to break the situation
Detailed explanation of MySQL binlog log and master-slave replication

Talk about data center network again

Code farming essential SQL tuning (Part 1)

收藏 |彻底搞懂感受野的含义与计算
随机推荐
Data enhancement
【愚公系列】2022年06月 .NET架构班 078-分布式中间件 ScheduleMaster的Worker集群
PostgreSQL create database
Learn automatic testing of postman interface from 0 to 1
[golang] leetcode special training - array and slice
大龄码农从北京到荷兰的躺平生活
laravel8 实现签到功能案例
Implementation of VGA protocol based on FPGA
Overview and example analysis of opengauss database performance tuning
MAUI 入门教程系列(1.框架简介)
Hands on, how should selenium deal with pseudo elements?
3000 words to teach you how to use mot
Db4ai: database driven AI
无心剑英汉双语诗001. 《春游》
laravel 8 通过 任务调度 实现 数据库备份
[daily question series]: how to test web forms?
Easy to use GS_ Dump and GS_ Dumpall command export data
Laravel 8 uses passport for auth authentication and token issuance
Go language - value types and reference types
Elk enterprise log analysis system