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

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

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

import java.util.*;
class ListNode {
    ListNode next;
    int val;
    public ListNode() {

    }
    public ListNode(int val) {
        this.val = val;
    }
}
public class Main {
  //使用双指针,快指针指向第k个节点,慢指针指向第一个节点,一起向下遍历
    public static void main(String[] args) {
        ListNode node = new ListNode();
        ListNode head = node;
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            for (int i = 1; i <= n; i++) {
                ListNode tmp = new ListNode(sc.nextInt());
                node.next = tmp;
                node = node.next;
            }
            int k = sc.nextInt();
            ListNode slow = head, quick = head;
            while (k-- != 0) {
                if (quick.next == null) {
                    System.out.println(-1);
                    return;
                }
                quick = quick.next;
            }
            while (quick != null) {
                slow = slow.next;
                quick = quick.next;
            }
            System.out.println(slow.val);
        }

    }
}

全部评论

相关推荐

感性的干饭人在线蹲牛友:🐮 应该是在嘉定这边叭,禾赛大楼挺好看的
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务