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

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

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

import java.util.Scanner;
import java.util.*;


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> listLengths = new ArrayList<>();// 存放多组数据
        ArrayList<int[]> listSums = new ArrayList<>();
        ArrayList<Integer> kLengths = new ArrayList<>();
        int num = 0;
        boolean flag = true;
        while (sc.hasNextLine()) { // 等待控制台,是否有输入
            String s = sc.nextLine().trim();// 获取输入
            if (Objects.equals(s, "")) {
                break;
            }
            if (num % 3 == 0) {
                listLengths.add(Integer.parseInt(s)); 
            } else if (num % 3 == 1) {
                listSums.add(Arrays.stream(s.split(" ")).mapToInt(Integer::parseInt).toArray());
            } else {
                kLengths.add(Integer.parseInt(s));
            }
            num++; // 变量存放位置
        }

//        int length = 8;
//        int[] arr = new int[]{1,2,3,4,5,6,7,8};
//        int k = 4;


        for (int i = 0; i < listLengths.size(); i++) {
            int length = listLengths.get(i);
            int[] arr = listSums.get(i);
            Integer k = kLengths.get(i);
            System.out.println(lastKValue(length, arr, k));
        }
    }

    private static Integer lastKValue(int length, int[] arr, int k) {
        if (length == 1) {
            return arr[0];
        }
        ListNode listNode = new ListNode();
        ListNode dumy = listNode; //拷贝地址
        for (int i = 0; i < length; i++) {
            listNode.next = new ListNode(arr[i]);
            listNode = listNode.next;
        }
        ListNode cur = dumy.next;

        // 输出倒数第K个节点,也就是顺数的 length-k,索引位置就是length-k-1
        ListNode res = null;
        for (int i = 0; i < length - k; i++) {
            res = cur.next;
            cur = res;
        }
        return res.value;
    }

    static class ListNode {
        Integer value;
        ListNode next;

        public ListNode(Integer value, ListNode next) {
            this.value = value;
            this.next = next;
        }

        public ListNode(Integer value) {
            this.value = value;
        }

        public ListNode() {
        }

        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public ListNode getNext() {
            return next;
        }

        public void setNext(ListNode next) {
            this.next = next;
        }
    }
}

全部评论

相关推荐

06-25 09:33
厦门大学 Java
球球别拷打俺了:现在日常估计没啥hc了,等到八月多估计就慢慢有了。双九✌🏻不用焦虑的
投递快手等公司10个岗位
点赞 评论 收藏
分享
07-29 12:14
门头沟学院 Java
程序员小白条:oppo不用想了,经常看92都挂的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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