链表中倒数第k个结点

来源:互联网 发布:java格式化时间字符串 编辑:程序博客网 时间:2024/05/20 19:45
/*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==nullptr || k <=0 || k>GetLength(pListHead))            return NULL;            ListNode *pFast = pListHead;        ListNode *pSlow = pListHead;               for(int i = 0;i < k-1;i++)            pFast = pFast->next;                while(pFast->next!=nullptr)        {            pFast = pFast->next;            pSlow = pSlow->next;        }                return pSlow;    }        int GetLength(ListNode *pListHead)    {     int length= 0;        while(pListHead)        {            pListHead = pListHead->next;            length++;        }        return length;    }};

0 0