zoukankan      html  css  js  c++  java
  • 链表中倒数第k个结点

    ##题目描述 输入一个链表,输出该链表中倒数第k个结点。

    思路

    快慢指针注意边界。
    时间复杂度O(n),空间复杂度O(1)。

    代码

    /*
    public class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }*/
    public class Solution {
        public ListNode FindKthToTail(ListNode head,int k) {
            if(head == null || k < 1)    return null;
            ListNode slow = head;
            ListNode fast = head;
            for(int i = 1; i < k; i++){
                if(fast.next == null) {
                    return null;
                }
                fast = fast.next;
            }
            while(fast.next != null) {
                slow = slow.next;
                fast = fast.next;
            }
            return slow;
        }
    }
    
  • 相关阅读:
    JZOJ.2117. 【2016-12-30普及组模拟】台风
    团队合作
    长沙游记
    统计
    html....
    OI之路
    三鑫普及组模拟赛
    牛顿迭代法
    台风
    gcd
  • 原文地址:https://www.cnblogs.com/ustca/p/12326941.html
Copyright © 2011-2022 走看看