首页 > 编程语言 > 详细

Java-找出单链表的倒数第k结点

时间:2015-06-09 17:32:43      阅读:192      评论:0      收藏:0      [点我收藏+]
/**
 * 两个指针,一个先走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;
	
}

Java-找出单链表的倒数第k结点

原文:http://blog.csdn.net/zhuyunhe/article/details/46426055

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!