题目描述
输入一个链表,输出该链表中倒数第 k 个结点。
注意:
k >= 1;
如果 k 大于链表长度,则返回 NULL;
样例
输入:链表:1->2->3->4->5 ,k=2
输出:4
使用快慢指针,快指针先走k步,然后慢指针与快指针一起走,直到快指针走到链表结尾,此时慢指针指向的位置为倒数k个节点。一些特殊情况,如果链表为空,那么返回nullptr,如果k的值大于链表的长度返回也是nullptr
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* findKthToTail(ListNode* pListHead, int k) {
if(!pListHead) return nullptr;
ListNode* fast = pListHead;
ListNode* slow = pListHead;
int n=k;
while(fast && n)
{
n--;
fast=fast->next;
}
if(n>0) return nullptr;
while(fast)
{
fast=fast->next;
slow=slow->next;
}
return slow;
}
};
class Solution {
public:
ListNode* findKthToTail(ListNode* head, int k) {
int n = 0;
for (auto p = head; p; p = p->next) n ++ ;
if (n < k) return nullptr;
auto p = head;
for (int i = 0; i < n - k; i ++ ) p = p->next;
return p;
}
};