当前位置:网站首页>JZ22 链表中倒数最后k个结点
JZ22 链表中倒数最后k个结点
2022-04-23 02:40: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://blog.csdn.net/pure_dreams/article/details/124342917
边栏推荐
- windows MySQL8 zip安装
- 1215_ Hello world used by scons
- Data warehouse construction table 111111
- Preliminary understanding of stack and queue
- Daily question (April 22, 2022) - rotation function
- 能做多大的单片机项目程序开发,就代表了你的敲代码的水平
- Understanding process (multithreading primary)
- Applet reads files
- 类初始化和实例初始化面试题
- 魔王冷饭||#078 魔王答上海、南京行情;沟通指导;得国和打杀筛选;赚钱的目的;改变别人看法
猜你喜欢

谷雨

The 16th day of sprint to the big factory, noip popularization Group Three Kingdoms game

能做多大的单片机项目程序开发,就代表了你的敲代码的水平

【无标题】

认识进程(多线程_初阶)

Download the genuine origin Pro 2022 tutorial and how to activate it

Hack the box optimum

Interpretation of the future development of smart agriculture

PTA: praise the crazy devil

Want to experience homekit smart home? Why don't you take a look at this smart ecosystem
随机推荐
本地远程访问云服务器的jupyter
谷雨
全局、獨享、局部路由守衛
IAR embedded development stm32f103c8t6 Lighting LED
Synchronized锁及其膨胀
Use of go language web Middleware
十六、异常检测
[chrome extender] content_ Cross domain problem of script
打靶narak
Push data from onenet cloud platform to database
类初始化和实例初始化面试题
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
Daily question (April 22, 2022) - rotation function
How to prevent leakage of operation and maintenance data
Renesas electronic MCU RT thread development and Design Competition
Rhcsa day 1 operation
wordpress 调用指定页面内容详解2 get_children()
Leetcode cooking
每日一题冲刺大厂第十六天 NOIP普及组 三国游戏
Fast and robust multi person 3D pose estimation from multiple views