标签:eve tno ati pre 单向链表 sys 时间复杂度 nod 现在
思路:利用快慢指针能实现在时间复杂度为O(n)的情况下,找到第k个节点
1,快指针先走k步
2,快慢指针一起走,直到快指针指向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); }
标签:eve tno ati pre 单向链表 sys 时间复杂度 nod 现在
原文地址:https://www.cnblogs.com/dongma/p/13236185.html