原文地址:https://www.jianshu.com/p/243980cc6b88

时间限制:1秒 空间限制:32768K

输入一个链表,输出该链表中倒数第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==nullptr || k<1)
            return nullptr;
        ListNode* fast=pListHead;
        ListNode* slow=pListHead;
        for(int i=0;i<k-1;i++){
            if(fast->next==nullptr)
                return nullptr;
            fast=fast->next;
        }
        while(fast->next){
            fast=fast->next;
            slow=slow->next;
        }
        return slow;
    }
};

运行时间:4ms
占用内存:472k

相关文章:

猜你喜欢
  • 2022-02-14
相关资源
相似解决方案