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

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

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

import java.util.*;

import java.io.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException{
       BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
       String str = null;
       while((str=bf.readLine())!=null){
            //获取原始输入
            int len = Integer.parseInt(str);
            String[] num = bf.readLine().split(" ");
            int want = Integer.parseInt(bf.readLine());
            //创建链表头节点
            ListNode ls = new ListNode();
            //头插法将新节点插入链表头
            for(int i=0;i<len;i++){
                ListNode newC = new ListNode(Integer.parseInt(num[i]),ls);
                //更新头节点
                ls = newC;
            }
            //从头开始遍历链表直至满足条件
            while(ls!=null && want !=1){
                ls = ls.next;
                want--;
            }
            //输出对应节点
            System.out.println(ls.num);

       }
    }
}

//自定义链表节类
class ListNode {
    int num;
    ListNode next;
    public ListNode(){}
    public ListNode(int l,ListNode n){
        this.num=l;
        this.next =n;
    }
}

全部评论

相关推荐

06-05 19:46
已编辑
武汉大学 后端
点赞 评论 收藏
分享
06-14 19:09
门头沟学院 Java
darius_:给制造业搞的,什么物料管理生产管理,设备管理点检,最最关键的就是一堆报表看板。个人觉得没啥技术含量都是些基本的crud,但是业务很繁琐那种
点赞 评论 收藏
分享
投递长鑫存储等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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