方法:双指针法 right指针先走K步,然后left,right指针一起走,当right = NULL,left指针到倒数第K个节点
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
struct ListNode
{
public:
int val;
struct ListNode *next;
};
class Solution
{
public:
// 14 链表中倒数第K个节点
// 双指针法
ListNode* FindKthToTail(struct ListNode* pListHead, int k) {
if (pListHead == NULL) {
return NULL;
}
int i = 0;
ListNode *right = pListHead;
//right指针先向前走k步
while (i < k && right != NULL) {
right = right->next;
i++;
}
if (right == NULL && i < k) {
return NULL;
}
ListNode *left = pListHead;
while (right != NULL) {
left = left->next;
right = right->next;
}
return left;
}
};
int main()
{
ListNode list[4];
list[0].val = 1;
list[0].next = &list[1];
list[1].val = 2;
list[1].next = &list[2];
list[2].val = 3;
list[2].next = &list[3];
list[3].val = 4;
list[3].next = NULL;
Solution solu;
ListNode* p = solu.FindKthToTail(list,3);
cout << p->val << endl;
return 0;
}