请问,我这段代码写完之后,运行起来为什么不能实现目的,返回为空?

代码如下
//找到单链表倒数第K个的元素

    public HeroNode find(int k) {
        int count=0;
        HeroNode temp=head.next;
        HeroNode cur=head.next;
        while(true) {
            if(temp==null) {
                break;
            }
            count++;
            temp=temp.next;        
        }
        int t=count;
        for(int i=0;i<t-k;i++) {
            cur=cur.next;
        }
        return cur;
    }
阅读 3.1k
5 个回答

一次循环搞定的事写了2次?

看不出什么问题啊

package a.b;

import java.util.Objects;

/**
 * @author zuojingang
 * @Title: Test
 * @Description: Todo
 * @date 2019-11-01 15:47
 */
public class Test {

    public static void main(String[] args) {

        HeroNode head = new HeroNode(new HeroNode(new HeroNode(new HeroNode(new HeroNode(new HeroNode(null, 5), 4), 3), 2), 1), 0);
        HeroNode target = find(head, 2);

        System.out.println(Objects.nonNull(target)? target.content: null);
    }

    public static HeroNode find(HeroNode head, int k) {
        int count=0;
        HeroNode temp=head.next;
        HeroNode cur=head.next;
        while(true) {
            if(temp==null) {
                break;
            }
            count++;
            temp=temp.next;
        }
        int t=count;
        for(int i=0;i<t-k;i++) {
            cur=cur.next;
        }
        return cur;
    }

    static class HeroNode{

        public HeroNode next;
        public int content;

        public HeroNode(HeroNode next, int content) {
            this.next = next;
            this.content = content;
        }
    }
}

WeChat68b267439e0e3754d6eaeb4ec415b861.png

思路没问题,肯定是边界没处理好,比如count = 1,或者i < t - k + 1这些试一试肯定能做出来。
这个题正确的思路是两个点第一个点走到k时,第二个点开始走,当第一个点next为null(走到头了),这时候第二个点就是你想要的

public void find(int k) {

    int count=0;//定义一个
    HeroNode temp=head.next;
    HeroNode cur=head.next;
    while(true) {
        if(temp==null) {
            break;
        }
        count++;
        temp=temp.next;        
    }
    int t=count;
    for(int i=0;i<t-k;i++) {
        cur=cur.next;
    }
    System.out.println(cur);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题