思路:利用快慢指针能实现在时间复杂度为O(n)的情况下,找到第k个节点
1,快慢指针共同指向头结点
2,快指针先走k步
3,快慢指针一起走,直到快指针指向null时,慢指针所在位置就是倒数第k个节点
public static void main(String[] args) { ListNode eight = new ListNode(8,null); ListNode sevent = new ListNode(7,eight); ListNode six = new ListNode(6,sevent); ListNode firth = new ListNode(5,six); ListNode fourth = new ListNode(4,firth); ListNode three = new ListNode(3,fourth); ListNode two = new ListNode(2,three); ListNode one = new ListNode(1,two); int k = 3; ListNode low = one; ListNode fast = one; while (k > 0){ fast = fast.next; k--; } while (fast != null){ fast = fast.next; low = low.next; } System.out.println(fast); System.out.println(low.val); }
static class ListNode{
public Integer val;
public ListNode next;
public ListNode(Integer val, ListNode next) {
this.val = val;
this.next = next;
}
}