当前位置:网站首页>JZ22 鏈錶中倒數最後k個結點
JZ22 鏈錶中倒數最後k個結點
2022-04-23 02:41:00 【Rosita.】
題目鏈接:鏈錶中倒數最後k個結點_牛客題霸_牛客網
注意點:
1.暴力查找:首先求鏈錶長度len,如果小於k,就返回空,不小於k,走len-k不,得出的就是k個比特置及後的元素
2.快慢指針:慢指針指向頭節點,快指針先走k步,大於鏈錶長度返回空,如果快指針走到尾,慢指針指向的就是k個節點。
目錄
方法一:暴力查找
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代碼中的類名、方法名、參數名已經指定,請勿修改,直接返回方法規定的值即可
*
*
* @param pHead ListNode類
* @param k int整型
* @return ListNode類
*/
ListNode* FindKthToTail(ListNode* pHead, int k) {
int len = 0;
ListNode *p = pHead;
while(p){
len++;
p = p->next;
}
if(len < k) return NULL;
p = pHead;
for(int i = 0 ; i < len-k; ++i){
p = p->next;
}
return p;
}
};
方法二:快慢指針
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代碼中的類名、方法名、參數名已經指定,請勿修改,直接返回方法規定的值即可
*
*
* @param pHead ListNode類
* @param k int整型
* @return ListNode類
*/
ListNode* FindKthToTail(ListNode* pHead, int k) {
ListNode* fast = pHead ,*slow = pHead;
//快指針先走k步
for(int i = 0; i < k; ++i){
if(fast != nullptr){
fast = fast->next;
}else{
return slow = nullptr;
}
}
while(fast){
fast = fast->next;
slow = slow->next;
}
return slow;
}
};
版权声明
本文为[Rosita.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230240052827.html
边栏推荐
- Understanding process (multithreading primary)
- day18--栈队列
- 魔王冷饭||#078 魔王答上海、南京行情;沟通指导;得国和打杀筛选;赚钱的目的;改变别人看法
- JVM类加载器
- 认识进程(多线程_初阶)
- Solve the problem that the registered Google email Gmail mobile number cannot be used for verification
- Devil cold rice 𞓜 078 devil answers the market in Shanghai and Nanjing; Communication and guidance; Winning the country and killing and screening; The purpose of making money; Change other people's op
- win查看端口占用 命令行
- Use of go language web Middleware
- Fashion MNIST 数据集分类训练
猜你喜欢
接口请求时间太长,jstack观察锁持有情况
Modify the content of MySQL + PHP drop-down box
C language 171 Number of recent palindromes
Renesas electronic MCU RT thread development and Design Competition
【unity3D】直播间滚动式弹幕效果
How many steps are there from open source enthusiasts to Apache directors?
JVM运行时数据区(一)
16、 Anomaly detection
C语言 171. 最近回文数
005_ redis_ Set set
随机推荐
JDBC JDBC
Log4j知识点记录
leetcode 烹饪料理
[untitled]
Rhcsa second day operation
grain rain
Handwritten memory pool and principle code analysis [C language]
Modification du contenu de la recherche dans la boîte déroulante par PHP + MySQL
MySQL JDBC programming
Fast and robust multi person 3D pose estimation from multiple views
[xjtu Computer Network Security and Management] session 2 Cryptographic Technology
Push data from onenet cloud platform to database
How to recognize products from the perspective of Dialectics
打靶narak
数仓建表111111
想用Mac学习sql,主要给自己个充足理由买Mac听听意见
mysql function函数语法
Store consumption SMS notification template
使用Go语言构建Web服务器
A domestic image segmentation project is heavy and open source!