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

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

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

快慢指针,fast先走k步,再同步行走

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            ListNode head = new ListNode(-1);
            for (ListNode node = head; n-- > 0; node = node.next) {
                node.next = new ListNode(in.nextInt());
            }
            int k = in.nextInt();
            ListNode fast, slow;
            for (fast = head; k-- > 0; fast = fast.next);
            for (slow = head; fast != null; fast = fast.next, slow = slow.next);
            System.out.println(slow.val);
        }
    }
}

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

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务