题解 | #链表中倒数第k个结点#
链表中倒数第k个结点
http://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
首先一次遍历计算出链表长度;然后从头开始遍历,遍历到k-i就返回(i为链表下标,从0开始)
public ListNode FindKthToTail (ListNode pHead, int k) {
// write code here
//先计算出长度,然后循环判断
ListNode dummy = new ListNode(0);
dummy.next = pHead;
ListNode temp = pHead;
int len = 0;
while(temp != null){
len++;
temp = temp.next;
}
ListNode cur = dummy.next;
int i = 0;
while(cur != null){
if(k == len - i){
return cur;
}else{
cur = cur.next;
i++;
}
}
return null;
}
阿里云工作强度 708人发布
