1、题目描述
输入一个链表,输出该链表中倒数第k个结点。
2、分析
最容易想到的办法就是,遍历一遍链表,得到其长度,然后就可以找到倒数第N个节点。还有一个方法是只遍历一遍链表,使用双指针,用一个指针先走K步,如果此时为空,说明K就是链表长度,这样返回第一个节点就好。如果不为空,这时第二个指针和第一个指针开始一起走,当第一个指针最后最后一个节点时,第二个指针刚好走到第K个元素。
3、代码
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(pListHead==NULL||k==0) return NULL;
ListNode* first=pListHead;
ListNode* second=pListHead;
int count=0;
while(first!=NULL){
first=first->next;
++count;
}
if(k>count) return NULL;
//if(k==count) return pListHead;
int target=count-k;
for(int i=0;i<target;++i){
second=second->next;
}
return second;
}
};
//双指针法
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(pListHead==NULL||k==0) return NULL;
ListNode* first=pListHead;
ListNode* second=pListHead;
for(int i=0;i<k-1;++i){
if(first->next!=NULL){
first=first->next;
}
else return NULL;
}
while(first->next!=NULL){
first=first->next;
second=second->next;
}
return second;
}
};
4、相关知识点
需要掌握双指针法。