题解 | 链表中倒数最后k个结点

链表中倒数最后k个结点

https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9

import java.util.*;

public class Solution {
    public ListNode FindKthToTail (ListNode pHead, int k) {
        //测试2{如果k为0}
        if(k == 0) return null;
        ListNode tmp = reverse(pHead);
        ListNode last = tmp;
        for(int i =1 ;i <k;i++){
            //测试1{如果k比链表还长}
            if(tmp == null) return null;
            tmp = tmp.next;
        }
        reverse(last);
        return tmp;
    }
    public ListNode reverse(ListNode root){
       ListNode pre = null;
       ListNode next = null;
       while(root != null){
            next = root.next;
            root.next = pre;
            pre = root;
            root = next;
       }
       return pre;
    }
}

全部评论

相关推荐

政委qqq:这道题在算法竞赛里唯一考的就是高精度,但是只能难住C++这类语言,Python直接a+b秒天秒地
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务