【剑指offer】面试题15 使用一次遍历查找到倒数第K个节点-java

节点代码和链表定义代码参加 Java单链表操作

【要求】

 单次遍历即返回实验结果

【解题思路】

使用两个指针 *p1 和p2=*(p1+k-1), 当p2变为尾节点时候,p1即为所需要的倒数第K个节点

【考察点】-代码的鲁棒性 (即程序能够判断输入是否合乎规范要求,并对不合要求的输入予以合理的处理


实现代码:在MyLInkList类中添加方法findKthToTail

public Node findKthToTail(Node head,int k){
		if(k==0||head==null){
			System.out.print("invalid input   ");
			return null;
			}
			
		Node pBefore=head;
		Node pBehind=head;
		for(int i=0;i<k-1;i++){
			//此代码段用于判断K是否大于链表的大小
			if(pBefore.next!=null)
			pBefore=pBefore.next;
			else
				return null;
		}
		//代码结束
		while(pBefore.next!=null){
			pBehind=pBehind.next;
			pBefore=pBefore.next;
		}
		return pBehind;
		
		
	}


测试代码:在TestLinklist.java中添加测试内容

Node Kth0=linklist.findKthToTail(null, 5);
		System.out.println(Kth0==null?Kth0:Kth0.value);
		//测试检索为0
		Node Kth1=linklist.findKthToTail(linklist.head, 0);
		System.out.println(Kth0==null?Kth1:Kth1.value);
		//测试尾节点
		Node Kth2=linklist.findKthToTail(linklist.head, 1);
		System.out.println(Kth2==null?Kth2:Kth2.value);
		//测试中间节点
		Node Kth3=linklist.findKthToTail(linklist.head, 3);
		System.out.println(Kth3==null?Kth3:Kth3.value);
		//测试首节点
		Node Kth4=linklist.findKthToTail(linklist.head, 5);
		System.out.println(Kth4==null?Kth4:Kth4.value);
		//测试超出size的检索
		Node Kth5=linklist.findKthToTail(linklist.head, 6);
		System.out.println(Kth5==null?Kth5:Kth5.value);


实验结果:

链表内容:5 7 12 11 10 
运行结果:
invalid input   null
invalid input   null
10
12
5
null




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值