链表中倒数第k个结点
题目描述
输入一个链表,输出该链表中倒数第k个结点。
/* 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 || k <=0 || k > GetLength(pListHead)) return NULL; ListNode *pSlow = pListHead; ListNode *pFast = pListHead; for(int i = 0;i < k-1;i++){ pFast = pFast->next; } while(pFast->next){ pFast = pFast->next; pSlow = pSlow->next; } return pSlow; } int GetLength(ListNode *pListHead){ int len = 0; ListNode *pBegin = pListHead; while(pBegin){ len++; pBegin=pBegin->next; } return len; } };