题目描述
输入一个链表,输出该链表中倒数第k个结点。
1 /* 2 * 题目描述 3 * 输入一个链表,输出该链表中倒数第k个结点。 4 */ 5 6 public class Main14 { 7 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 ListNode head =new ListNode(0); 11 ListNode[] p =new ListNode[6]; 12 for(int i=0;i<p.length;i++) { 13 p[i] =new ListNode(i); 14 if(i>0) { 15 p[i-1].next = p[i]; 16 }else { 17 head.next = p[0]; 18 } 19 } 20 ListNode result = Main14.FindKthToTail(head, 2); 21 System.out.println(result.val); 22 } 23 24 25 public static class ListNode { 26 int val; 27 ListNode next = null; 28 29 ListNode(int val) { 30 this.val = val; 31 } 32 } 33 34 public static ListNode FindKthToTail(ListNode head,int k) { 35 if (head == null) { 36 return null; 37 } 38 39 int count = 1; 40 ListNode old = head; 41 while(head.next != null) { 42 head = head.next; 43 count++; 44 } 45 if (k > count) { 46 return null; 47 } 48 for(int i=0;i<count-k;i++) { 49 old = old.next; 50 } 51 return old; 52 } 53 }