节点代码和链表定义代码参加 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