题目描述
输入一个链表,输出该链表中倒数第k个结点。
思路:首先计算出链表的长度,再计算出倒数第k个是正数第几个,找到该结点即可。
1 public ListNode FindKthToTail(ListNode head,int k) { 2 if(head==null) 3 return head; 4 ListNode list=head; 5 int count=0; 6 while(list!= null) { 7 count++; 8 list=list.next; 9 } 10 if(count<k) 11 return null; 12 ListNode node=head; 13 for (int i=0;node!=null&&i<count-k;i++) 14 { 15 node = node.next; 16 } 17 return node; 18 19 }