题目
https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
我的思路
先找到链表的总结点数,再从头推到cnt-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* node=head;
int cnt=0;
while(head){
head=head->next;
cnt++;
}
for(int i=0;i<cnt-k;i++){
node=node->next;
}
return node;
}
};
双指针思路
使用快慢指针,慢指针指向第一个结点,快指针指向最后一个结点。两个指针保持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* slow=head,*fast=head;
for(;k>0;k--)
fast=fast->next;
while(fast){
slow=slow->next;
fast=fast->next;
}
return slow;
}
};