当前位置:网站首页>【每日一题】【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;
}
};边栏推荐
猜你喜欢

MySQL 原理与优化:Update 优化

An ABAP tool that can print the browsing history of a user in the system for BSP applications

It is reported that the original Meitu executive joined Weilai mobile phone, the top product may exceed 7,000 yuan

消息称原美图高管加盟蔚来手机 顶配产品或超7000元

推荐几款最好用的MySQL开源客户端,建议收藏!

Redis -- Nosql

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

Redis -- Nosql

Containerization | Scheduled Backups in S3

A test tool for ABAP Development Tool custom service endpoint
随机推荐
NPM - Cannot read properties of null (reading 'pickAlgorithm') 解决方案
Based on Azuki Series: NFT Valuation Analysis Framework "DRIC"
MySQL batch update and batch update method of different values of multiple records
Opencv 图像超像素分割(SLIC、SEEDS、LSC)
$'\r': command not found
Systemui status bar to add a new icon
It is reported that the original Meitu executive joined Weilai mobile phone, the top product may exceed 7,000 yuan
systemui shield notification bar
MySQL 原理与优化:Update 优化
Redis -- Nosql
systemui屏蔽通知栏
Mobileye携手极氪通过OTA升级开启高级驾驶辅助新篇章
匿名函数和全部内置函数详细认识(下篇)
Methodology of multi-living in different places
const修饰的指针变量(详解)
Zijin Example
Allwinner V853 development board transplants LVGL-based 2048 games
pm2 static file service
[Semantic Segmentation] DeepLab Series
TestLink导出用例转换工具