1. 程式人生 > >【劍指offer】輸出鏈表倒數第K個元素

【劍指offer】輸出鏈表倒數第K個元素

ndk head 判斷 result i++ != == col list

 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 }

【劍指offer】輸出鏈表倒數第K個元素