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

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

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

import java.util.*;

public class Main {

    private int size; 
    private ListNode head;

    private class ListNode {
        int val;
        ListNode next;
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }  

    public Main(int size, int[] array) {
        this.size = size;
        this.head = new ListNode(array[0]);

        ListNode p = head;
        for (int i = 1; i < size; i++) {
            p.next = new ListNode(array[i]);
            p = p.next;
        }
    }

    public ListNode findKthToTail(int k) {
        // 题目没有指出,无法理解
        if (k == 0) return new ListNode(0);
        if (k < 0 || k > size) return null;
        k = size - k;
        ListNode p = head;
        while (k != 0) {
            p = p.next;
            k--;
        }
        return p;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = Integer.parseInt(in.next());
            int[] array = new int[n];
            for (int i = 0; i < n; i++) {
                array[i] = Integer.parseInt(in.next());
            }
            int k = Integer.parseInt(in.next());
            Main solution = new Main(n, array);
            ListNode node = solution.findKthToTail(k);
            if (node != null) {
                System.out.println(node.val);
            }
            else {
                System.out.println();
            }
        }
    } 
}
全部评论

相关推荐

11-28 17:48
中山大学 C++
点赞 评论 收藏
分享
11-27 17:08
已编辑
牛客_产品运营部_私域运营
腾讯 普通offer 24k~26k * 15,年包在36w~39w左右。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
9
2
分享
牛客网
牛客企业服务