描述
输入一个长度为 n 的链表,设链表中的元素的值为 ai ,返回该链表中倒数第k个节点。
如果该链表长度小于k,请返回一个长度为 0 的链表。
数据范围:0≤n≤10^5,0≤ai≤10^9,0≤k≤10^9
要求:空间复杂度 O(n),时间复杂度 O(n)
进阶:空间复杂度 O(1),时间复杂度 O(n)
例如输入{1,2,3,4,5},2时,对应的链表结构如下图所示:
其中蓝色部分为该链表的最后2个结点,所以返回倒数第2个结点(也即结点值为4的结点)即可,系统会打印后面所有的节点来比较。
我的原解法:
class Solution {
public:
ListNode* FindKthToTail(ListNode* pHead, int k) {
// write code here
if(pHead) return pHead;
auto p = pHead;
int i = 0;
while(p){
i++;
p=p->next;
}
i = i-k;
if(i<0) return p;
while(i>0){
pHead=pHead->next;
i--;
}
return pHead;
}
};
讨论区解法1(双指针):
class Solution {
public:
ListNode* FindKthToTail(ListNode* pHead, int k) {
// write code here
auto p = pHead;
while(k--){
if(!p)
return p;
p=p->next;
}
while(p){
p=p->next;
pHead=pHead->next;
}
return pHead;
}
};
讨论区解法2:
class Solution {
public:
ListNode* FindKthToTail(ListNode* pHead, int k) {
ListNode* res=nullptr;
vector<ListNode*> insertNode;
while(pHead){
insertNode.push_back(pHead);
pHead=pHead->next;
}
if(insertNode.size()<k) return res;
return insertNode[insertNode.size()-k];
}
};