算法1
思路:像这种链表倒数第k个y元素,位置是n-k;
一般需要计数,int n=0;for(auto p=head;p;p=p->next)n++;然后for(int i=0;i[HTML_REMOVED]next;
C++ 代码
/**
* 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) {
int n=0;
for(auto p=pListHead;p;p=p->next)n++;
if(k>n)return NULL;
auto p=pListHead;
for(int i=0;i<n-k;i++ )p=p->next;
return p;
}
};