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

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

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

import java.util.*;
public class Main {
    public static class ListNode {
        public int val;
        public ListNode next;
        public ListNode(int val) {
            this.val = val;
        }
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {
            int n = Integer.valueOf(scan.nextLine().trim());
            String[] nums = scan.nextLine().split(" ");
            int k = Integer.valueOf(scan.nextLine().trim());
            ListNode head = createList(nums);
            find(head, k);
        }
    }
    // 自定义一个函数,实现链表的创建
    public static ListNode createList(String[] nums) {
        ListNode head = new ListNode(1);
        ListNode node = new ListNode(1);
        for (int i = 0; i < nums.length; i++) {
            if (i == 0) {
                head = new ListNode(Integer.valueOf(nums[i]));
                node = head;
                continue;
            }
            node.next = new ListNode(Integer.valueOf(nums[i]));
            node = node.next;
        }
        node.next = null;
        return head;
    }
    // 自定义一个函数,找到链表的倒数第 k 个节点
    public static void find(ListNode head, int k) {
        ListNode node = head;
        int len = 0;
        while (null != node) {
            len++;
            node = node.next;
        }
        int ans = 0;
        node = head;
        for (int i = 1; i <= len - k + 1; i++) {
            ans = node.val;
            node = node.next;
        }
        System.out.println(ans);
    }
}
全部评论
该牛油正在参与牛客写题解薅羊毛的活动,牛币,周边,京东卡超多奖品放送,活动进入倒计时!快来捡漏啦https://www.nowcoder.com/discuss/888949?source_id=profile_create_nctrack&channel=-1
点赞 回复 分享
发布于 2022-04-20 16:58

相关推荐

白火同学:能。我当初应届沟通了1200,收简历50,面试10左右吧,加油投吧
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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