zoukankan      html  css  js  c++  java
  • 链表中倒数第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;
        }
    };
  • 相关阅读:
    李超线段树 (Li-Chao Segment Tree)
    NowCoder Contest 894
    AtCoder Beginning Contest 126
    华工软院IBM LinuxONE Community Cloud云计算实验文档
    Codeforces Round #561 (div. 2)
    Comet OJ Contest #3
    Codeforces Edu Round 65 (Rated for Div. 2)
    莫队算法 (Mo's Algorithm)
    Codeforces Round #559 (Div. 2)
    GDCPC2019 广东省赛总结
  • 原文地址:https://www.cnblogs.com/whiteBear/p/12494843.html
Copyright © 2011-2022 走看看