package CountDownListNode; public class CountDown { public class ListNode { int val; ListNode next; ListNode (int x) { val = x; } } public ListNode getKthFromEnd(ListNode head , int k) { ListNode front = head , behind = head; while(front != null && k>0) { front = front.next; k --; } while(front !=null) { front = front.next; behind = behind.next; } return behind; } public ListNode buildLinkedList(int[] nums) { ListNode dummy = new ListNode(0); ListNode curr = dummy; for (int num : nums) { ListNode newNode = new ListNode(num); curr.next = newNode; curr = curr.next; } return dummy.next; } } public class Main { public static void main(String[] args) { CountDown countDown = new CountDown(); int[] nums = {1, 2, 3, 4, 5}; ListNode head = countDown.buildLinkedList(nums); int k = 2; ListNode kthFromEnd = countDown.getKthFromEnd(head, k); System.out.println("The " + k + "th node from the end is: " + kthFromEnd.val); } }


原文地址: http://www.cveoy.top/t/topic/pYk6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录