一、问题描述
输入一个链表,输出该链表中倒数第k个结点。
二、思路
最主要在到k-1位置前需要考虑指针域为空的情况。
三、代码
/*
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 *pHead = pListHead;
ListNode *pBehind = NULL;
for(unsigned int i = 0; i < k - 1; ++i){
if(pHead -> next != NULL){
pHead = pHead -> next;
}else{
return NULL;
}
}
pBehind = pListHead;
while(pHead -> next != NULL){
pHead = pHead -> next;
pBehind = pBehind -> next;
}
return pBehind;
}
};