单链表的倒数第k个结点

时间:2021-02-20 12:07:47   收藏:0   阅读:32

单链表的倒数第k个结点

1、题目描述

2、解题思路

3、代码

public static ListNode getKthFromEnd(ListNode head, int k){
?
    // 链表长度
    int listLength = getLength(head);
    // 判断k的有效性
    if (k <= 0 || k > listLength){
        return null;
    }
    // 遍历单链表
    int index = 0;
    ListNode current = head;
    while (current != null){
        // 倒数索引
        int countDownIndex = listLength - index;
?
        if (countDownIndex == k){
            return current;
        }
?
        current = current.next;
        index ++;
    }
    return null;
}
?
// 求链表长度
public static int getLength(ListNode node){
?
    if (node == null){
        return 0;
    }
?
    int length = 0;
    ListNode temp = node;
    while(temp != null){
        length ++;
        temp = temp.next;
    }
?
    return length;
}

 

 



原文:https://www.cnblogs.com/LittleSkinny/p/14419537.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!