当前位置:网站首页>【每日一题】【leetcode】26. 链表-链表中倒数第k个节点
【每日一题】【leetcode】26. 链表-链表中倒数第k个节点
2022-08-10 15:04:00 【aneutron】
题目
输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。 难易程度:easy
示例 1:
给定一个链表: 1->2->3->4->5, 和 k = 2. 返回链表 4->5.
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
分析
本题典型的双指针题目:
- 设指针
rp、lp都指向head, rp先走k步rp、lp同步移动- 到
rp指向链表尾后NULL的时候,lp即是倒数第k个节点
时间复杂度:O(N) 空间复杂度:O(1)
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode *lp = head, *rp = head;
while (rp != NULL) {
rp = rp->next;
if (k > 0) {
k--;
} else {
lp = lp->next;
}
}
return lp;
}
};上述算法,可以进一步优化,rp只先走k-1步,最后rp指向链表的最后一个节点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode *lp = head, *rp = head;
while (rp->next != NULL) {
rp = rp->next;// 结束时,rp是最后一个节点,而非NULL
if (k > 1) {
k--;
} else {
lp = lp->next;
}
}
return lp;
}
};边栏推荐
猜你喜欢

数据在内存中的存储

【语义分割】DeepLab系列

一个 ABAP 工具,能打印系统里某个用户对 BSP 应用的浏览历史记录

Rich Dad Poor Dad Reading Notes

SWIG教程《二》

持续集成实战 —— Jenkins自动化测试环境搭建

dedecms支持Word内容自动导入

Recommend a few had better use the MySQL open source client, collection!

FP6378AS5CTR SOT - 23-5 effective 1 mhz2a synchronous buck regulator

Parse the value of uuid using ABAP regular expressions
随机推荐
Understanding_Data_Types_in_Go
Appium for APP automation testing
宝塔面板开放Redis给指定外网机器
SWIG教程《二》
systemui shield notification bar
SWIG教程《一》
Software Test Cases
Community News——Congratulations to Dolphin Scheduling China User Group for 9 new "Community Administrators"
MySQL batch update and batch update method of different values of multiple records
Scala collections
pytest框架优化
SYM32——RTC实时时钟程序讲解
Zhaoqi Technology Innovation High-level Talent Entrepreneurship Competition Platform
FP6378AS5CTR SOT - 23-5 effective 1 mhz2a synchronous buck regulator
颜色空间
“低代码”编程或将是软件开发的未来
How to code like a pro in 2022 and avoid If-Else
E. Cross Swapping (and check out deformation/good questions)
Basic learning of XML
Go Context基本使用