链表中倒数第k个结点

时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M

题目描述

输入一个链表,输出该链表中倒数第k个结点。
 
思路:
  一个单链表,要输出倒数第k个结点,设立两个指针prePoint、lastPoint,让先行指针prePoint先走k-1次,然后lastPoint再和prePoint一起走
/*
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 *left = pListHead,*right = pListHead;
        for(int i = 0;i < k-1;i++)
        {
            if(left->next)
                left = left->next;
            else
                return NULL;
        }
        while(left->next)
        {
            right = right ->next;
            left = left->next;
        }
        return right;
    }
};

简化代码,也是目前最简洁、最一目了然的代码

/*
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 *prePoint = pListHead,*lastPoint= pListHead;
        int i = 0;
        while(prePoint != NULL)
        {
            if(i >= k)
            {
                lastPoint = lastPoint->next;
            }
            prePoint = prePoint->next;
            i++;
        }
        return i < k?NULL:lastPoint;
    }
};

 

 

posted @ 2020-03-14 22:29  牛犁heart  阅读(106)  评论(0编辑  收藏  举报