• 链表中倒数第k个结点


    原文地址: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

  • 相关阅读:
    UVa
    UVa
    USACO
    USACO
    USACO
    Floyed算法学习
    POJ
    POJ
    codeforces 796C Bank Hacking
    codeforces 796B Find The Bone
  • 原文地址:https://www.cnblogs.com/cherrychenlee/p/10780958.html
Copyright © 2020-2023  润新知