题解 | #输出单向链表中倒数第k个结点#

输出单向链表中倒数第k个结点

https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

好多解答完全不看题目要求的
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            int a = Integer.valueOf(in.nextLine());
            //第一行,也就是链表长度
            String s = in.nextLine();
            Scanner sc = new Scanner(s);
            //第二行,每个链表节点
            int c = Integer.valueOf(in.nextLine());
            //第三行,c
            ListNode headNode = new ListNode(-1);
            ListNode temp = headNode;
            while (a > 0) { // 正序构建链表
                int b = sc.nextInt();
                temp.next = new ListNode(b);
                temp = temp.next;

                if (a == c) {//返回倒数第c个结点指针
                    System.out.println(temp.key);
                }

                a--;//构建后要忘记链表长度
            }
        }
    }

}
class ListNode {
    Integer key;
    ListNode next;

    // 有参构造函数
    public ListNode(Integer key) {
        this.key = key;
        this.next = null;//异常返回空指针
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务