輸入一個鏈表,輸出該鏈表中倒數第k個結點。this
本題主要注意如下幾點:
code
/*function ListNode(x){ this.val = x; this.next = null; }*/ function FindKthToTail(h, k) { if(h === null || k <= 0) return null; var len = 0; var cur = h; while(cur !== null) { len++; cur = cur.next; } if(k > len){ return null; } var index = len - k + 1; cur = h; while(index !== 1){ cur = cur.next; index--; } return cur; }