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

来源:互联网 发布:淘宝手机端店招尺寸 编辑:程序博客网 时间:2024/05/16 14:38

节点代码和链表定义代码参加 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;elsereturn 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);//测试检索为0Node 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   nullinvalid input   null10125null




0 0
原创粉丝点击