剑指offer14链表中倒数第k个结点

输入一个链表,输出该链表中倒数第k个结点。

class Solution {

public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        if(pListHead==NULL||k==0)
            return NULL;
        ListNode* pHead=pListHead,*pTail=pListHead;
        for(int i=1;i<k;++i)
        {
            if(pHead->next!=NULL)
            {
                pHead=pHead->next;
            }
            else
                return NULL;
        }
        while(pHead->next!=NULL)
        {
            pHead=pHead->next;
            pTail=pTail->next;
        }
        return pTail;
    }
};

猜你喜欢

转载自blog.csdn.net/u014532829/article/details/79972124