面试题:找出单链表倒数第N个元素

       第一种方法先求出元素个数,在遍历元素个数-n个,时间复杂度为:O(N+N-n)=O(2N-n)。

       第二种设置俩个指针,第一个先走N步,第二个开始走。俩者速度一样,时间复杂度为O(N)。

代码如下:

package dataStructtion.linear;
/**
 * 获取单链表倒数第N个元素
 * @author xiucai
 */
public class SingleLinkedList_LastN {
	/**
	 * 第一种方法先求出元素个数,在遍历元素个数-n个
	 * 时间复杂度为:O(N+N-n)=O(2N-n)
	 * @param list
	 * @param n
	 * @return
	 * @throws Exception
	 */
	public static<T> T getLastN1(SingleLinkedList<T> list,int n) throws Exception{
		int count=0;
		Node<T> node=list.head;
		while(node.next!=null){
			count++;
			node=node.next;
		}
		if(count<n)
			throw new Exception("单链表元素个数小于 "+n+" !");
		node=list.head;
		for(int i=0;i<count-n;i++){
			node=node.next;
		}
		return (T)node.data;
	}
	
	/**
	 * 设置俩个指针,第一个先走N步,第二个开始走。俩者速度一样
	 * 时间复杂度为O(N)
	 * @param list
	 * @param n
	 * @return
	 * @throws Exception 
	 */
	public static<T> T getLastN2(SingleLinkedList<T> list,int n) throws Exception{
		//fastN先走N步,slowN等fastN走N步后在开始走
		Node<T> fastN=list.head,slowN=list.head;
		for(int i=0;i<n;i++){
			if(fastN.next==null){
				throw new Exception("单链表元素个数小于 "+n+" !");
				/*try {
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
			}
			fastN=fastN.next;
		}
		while(fastN.next!=null){
			fastN=fastN.next;
			slowN=slowN.next;
		}
		return (T)slowN.data;
	}
	//测试方法
	public static void main(String[] args) throws Exception {
		SingleLinkedList<String> list=new SingleLinkedList<String>();
		for(int i=1;i<=100;i++){
			list.append("第"+i+"个");
		}
		System.out.println(getLastN2(list, 1000));
	}
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值