JZ22 链表中倒数最后k个节点

image
image

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* FindKthToTail(ListNode* pHead, int k) {
        // write code here

        //思路:首先获取链表的长度n,然后让链表往前走n-k步,然后返回最后k个节点

        int length = GetLengthOfList(pHead);
        int len = length - k;
        if(length < k)
            return nullptr;
        else
         {
            while (len) {
                pHead = pHead->next;
                len--;
            }
            return pHead;
         }
 
    }

    int GetLengthOfList( ListNode* pHead)
    {
        int i=0;
        while (pHead) {
            i++;
            pHead = pHead->next;
        }
        return i;
    }
};
posted @ 2024-04-12 19:00  蓝色的海嗷  阅读(27)  评论(0)    收藏  举报