CCI 2.2 找出单向链表中倒数第k个结点

实现一个算法,找出单向链表中倒数第k个结点。

package test;

public class KthNode {
	//快慢指针
	public Node kthNode(Node head, int k){
		if(head==null || k<=0)
			return null;
		Node slow, fast;
		slow = fast = head;
		while(k>0){
			if(fast==null)
				return null;
			fast = fast.next;
			k--;
		}
		while(fast != null){
			fast = fast.next;
			slow = slow.next;
		}
		return slow;
	}
}


你可能感兴趣的:(链表)