当前位置:网站首页>Sword finger offer 22 The penultimate node in the linked list - speed pointer
Sword finger offer 22 The penultimate node in the linked list - speed pointer
2022-04-23 17:33:00 【hequnwang10】
One 、 Title Description
Enter a linked list , Output the last number in the list k Nodes . In order to conform to the habits of most people , From 1 Start counting , That is, the tail node of the list is the last 1 Nodes .
for example , A list has 6 Nodes , Start from the beginning , Their values, in turn, are 1、2、3、4、5、6. The last of the list 3 Each node has a value of 4 The node of .
Example 1:
Given a linked list : 1->2->3->4->5, and k = 2.
Back to the list 4->5.
Two 、 Problem solving
Speed pointer
There is a difference between the speed pointer and the slow pointer K Nodes , Then update the speed pointer
/** * 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) {
// Speed pointer
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://yzsam.com/2022/04/202204231732009222.html
边栏推荐
- C语言程序设计之函数的构造
- The system cannot be started after AHCI is enabled
- 双闭环直流调速系统matlab/simulink仿真
- Use of five routing guards
- 958. 二叉树的完全性检验
- EF core in ASP Generate core priority database based on net entity model
- Clickhouse SQL operation
- 01 - get to know the advantages of sketch sketch
- Generating access keys using JSON webtoken
- 2021长城杯WP
猜你喜欢
随机推荐
Indexes and views in MySQL
双闭环直流调速系统matlab/simulink仿真
练习:求偶数和、阈值分割和求差( list 对象的两个基础小题)
线性代数感悟之1
Abnormal resolution of Xiaomi camera
402. 移掉 K 位数字-贪心
Shell-sed命令的使用
基于51单片机红外无线通讯仿真
ClickHouse-SQL 操作
ASP. Net core configuration options (Part 2)
For the space occupation of the software, please refer to the installation directory
Use of todesk remote control software
Use of shell sed command
为什么有些人说单片机简单,我学起来这么吃力?
SiteServer CMS5. 0 Usage Summary
[related to zhengheyuan cutting tools]
Shell-入门、变量、以及基本的语法
How to manually implement the mechanism of triggering garbage collection in node
[difference between Oracle and MySQL]
ASP. Net core configuration options (Part 1)