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

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

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

import java.util.Scanner;
public class Main {
    public static void main(String[] args) { 
        Scanner in = new Scanner(System.in);
        while(in.hasNextInt()){
            int n = in.nextInt();
            int[] data = new int[n];
            for(int i = 0; i<n; i++){
                data[i] = in.nextInt();
            }
            int rearIndex = in.nextInt();
            ListNode head = new ListNode(0,null);
            for(int i = 0; i<n; i++){
                ListNode node = head;
                    while(node.next != null){
                        node = node.next;
                    }
                node.next = new ListNode(data[i],null);
            }   
            ListNode no = head.next;
            if(rearIndex==0){
                System.out.println(0);
            }else{
                for(int j = 0; j<n-rearIndex; j++){
                    no = no.next;
                }
            System.out.println(no.key);
            }
        } 
    }
}
class ListNode{
    int key;
    ListNode next;
    ListNode(int key, ListNode n){
        this.key = key;
        this.next = n;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-27 15:19
简历上能写3个月吗?
码农索隆:大胆写,主要你能把实习经历包装好,可以看一下我这篇帖子https://www.nowcoder.com/share/jump/4888395581180798063
点赞 评论 收藏
分享
05-22 09:23
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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