privatestaticclassSolution{ public ListNode getKthFromEnd(ListNode head, int k){ int size = 0; ListNode temp = head; while (temp.next != null) { size++; temp = temp.next; } size = size - k + 1; while (size-- > 0) { assert head != null; head = head.next; } return head; } }
双指针:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
privatestaticclassSolution2{ public ListNode getKthFromEnd(ListNode head, int k){ ListNode fast = head; ListNode slow = head; for (int i = 0; i < k - 1; i++) { fast = fast.next; }
while (fast.next != null) { slow = slow.next; fast = fast.next; }