【剑指offer】输出链表倒数第K个元素

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode FindKthToTail(ListNode head,int k) {
12         if(head == null) return null;
13         int length = 0;
14         ListNode tempNode = head;
15         ListNode result;
16         while(tempNode!=null){
17             length++;
18             tempNode = tempNode.next;
19         }
20         //判断K值是否合法
21         if(k > length) return null;
22         tempNode = head;
23         for(int i=0; i<length; i++){
24             if(i>=k){
25                 head = head.next;
26             }
27             tempNode  = tempNode.next;
28         }
29         return head;
30     }
31 }

猜你喜欢

转载自www.cnblogs.com/singular/p/10030032.html
今日推荐