import java.util.*; public class Main { public static int findKnd(ListNode node, int k) { ListNode prep = node; ListNode curr = node; for(int i = 0; i < k; i++) { prep = prep.next; } while(prep != null) { prep = prep.next; curr = curr.next; } return curr.val; } public static void main(String[] args) { ListNode node = new ListNode(1); node.next = new ListNode(2); node.next.next = new ListNode(1); node.next.next.next = new ListNode(3); node.next.next.next.next = new ListNode(2); node.next.next.next.next.next = new ListNode(5); printList(node); System.out.println(findKnd(node, 3)); return; } //自己创建的结构要自己注意打印; public static void printList(ListNode node) { while(node != null) { System.out.print(node.val); node = node.next; } System.out.println('.'); } }
Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list.
最新推荐文章于 2019-04-14 03:48:06 发布