链表中倒数第k个节点

简要描述一下思路:

  遍历第一遍,得到链表节点总个数count;第二次遍历count - k次即可(需要注意一下条件的判定)

  下面贴代码:

/**
 * 输入一个链表,尝试输出该链表中的倒数第k个节点
 *
 * @author ihaokun
 * @date 2019/7/22 20:47
 */
public class LinkedListReciprocalElement {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        System.out.println(findKthToTail(head, 4).val);
    }
    public static ListNode findKthToTail(ListNode head, int k){
        int count = 0;
        ListNode temp = head;
        while(temp != null){
            count++;
            temp = temp.next;
        }
        if (k <= count){
            for (int i = 0; i < (count - k); i++) {
                head = head.next;
            }
        } else {
            head = null;
        }
        return head;
    }
}

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

后面看到一个更简单的方法,使用的是2个链表节点,只需要遍历一次即可;后续补上这种写法

原文地址:https://www.cnblogs.com/ihaokun/p/11228693.html