题目描述
输入一个链表,输出该链表中倒数第k个结点。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
ListNode* a = pListHead;
ListNode* b = pListHead;
if(pListHead == NULL)
{
return NULL;
}
int node = 0;
while(a!=NULL)
{
a = a->next;
node++;
}
if(k > node)
{
return NULL;
}
int m = node - k;
for(int i =0;i < m;i++)
{
b = b->next;
}
return b;
}
};
class Solution {
public:
ListNode* FindKthToTail(ListNode* p, unsigned int k) {
//if(!p) return nullptr;
auto p1=p;
for(int i=0;i!=k;++i)
if(!p1)return nullptr;
else
p1=p1->next;
while(p1){
p1=p1->next;
p=p->next;
}
return p;
}
};
本文介绍了一种高效算法来找到链表中倒数第K个节点的方法。通过两次遍历或双指针技巧,确保了算法的简洁性和易实现性。
7360

被折叠的 条评论
为什么被折叠?



