Java-找出單鏈表的倒數第k結點

/**
 * 兩個指針,一個先走k-1步,然後兩個同時向後移動,當提前走的指針移動到鏈表尾部時,落後的那個指針正好是要找的節點
 * @param root
 * @param k
 * @return
 */
public static ListNode findKthTotail(ListNode root,int k){
	if(root==null || k<=0){
		return null;
	}
	
	ListNode ahead = root;
	ListNode behind = root;
	
	for(int i=0; i<k-1; i++){
		if(ahead.getNext() != null){
			ahead = ahead.getNext();
		} else{
			return null;
		}
	}
	
	while(ahead.getNext() != null){
		ahead = ahead.getNext();
		behind = behind.getNext();
	}
	
	return behind;
	
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章