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

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

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
 public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        in.useDelimiter("\n");
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            int length = in.nextInt();
            String data = in.next();

            String[] split = data.split(" ");
            ListNode pNode = new ListNode();
            ListNode head = new ListNode();

            for(int i = split.length - 1; i >= 0; i --) {
                if(i != split.length - 1) {
                    pNode = pNode.m_pNext;
                }
                ListNode node = new ListNode();
                node.m_nKey = Integer.parseInt(split[i]);
                pNode.m_pNext = node;
                if(i == split.length - 1) {
                    head.m_pNext = node;
                }
            }
            int no = in.nextInt();

            for(int i = 1; i <= no; i ++) {
                head = head.m_pNext;
            }
            System.out.println(head.m_nKey);

        }
    }

    static class ListNode {
        int m_nKey;
        ListNode m_pNext;
    };
}

全部评论

相关推荐

06-26 18:30
门头沟学院 Java
据说名字越长别人越关...:你问问这里面有多少是正经候选人,而不是乱打招呼的
点赞 评论 收藏
分享
自学java狠狠赚一...:骗你点star的,港卵公司,记得把star收回去
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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