解题思路:
第一个方法就是最常规的,遍历一遍找长度,再遍历一遍找倒数第k个,代码如下:
/**
* 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) {
int len = 0;
ListNode * demo = head;
while(demo != nullptr) {
demo = demo -> next;
len ++;
}
int i = len - k;
while(i --) {
head = head -> next;
}
return head;
}
};
快慢指针的方法是更为精妙的,让快指针永远比慢指针快k个节点,那么快指针到末尾的时候,慢指针刚好到倒数第k个,代码如下:
/**
* 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* fast = head;
ListNode* slow = head;
int i = k;
while(k --) {
fast = fast -> next;
}
while(fast != nullptr) {
fast = fast -> next;
slow = slow -> next;
}
return slow;
}
};