给出一个链表如何找到倒数第k个元素,有两种思路,1.直接遍历链表统计出节点个数n.然后再从头遍历到第n-k个元素。但此时最坏时间复杂度有O(2n)非常烂。
2.使用一前一后两个指针,让第一个先走k步,然后两个指针一起走 直到前一个指针到达终点。
#include <iostream>
using namespace std;
struct listNode
{
int value;
listNode* next;
};
listNode *findLastKthNode(listNode * head,int k)
{ if(k<=0)
return NULL;
listNode *front=head,*behind=head;
int i=0;
while(front!=NULL&&i<k)
{
front=front->next;
i++;
}
if(front==NULL)
return NULL;
while(front!=NULL)
{
front=front->next;
behind=behind->next;
}
return behind;
}