力扣题目:LCR 140. 训练计划 II - 力扣(LeetCode)
给定一个头节点为 head
的链表用于记录一系列核心肌群训练项目编号,请查找并返回倒数第 cnt
个训练项目编号。
示例 1:
输入:head = [2,4,7,8], cnt = 1 输出:8
提示:
1 <= head.length <= 100
0 <= head[i] <= 100
1 <= cnt <= head.length
算法如下:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
import java.util.ArrayList;
import java.util.List;public class Solution {public ListNode trainingPlan(ListNode head, int cnt) {List<ListNode> list=new ArrayList<>();if(head==null){//头结点为空直接返回return null;}else {//将链表数据赋值到列表ListNode curP=head;while (curP!=null){list.add(curP);curP=curP.next;}}if(cnt>list.size()){//不存在返回空return null;}else {//存在返回倒数数据return list.get(list.size()-cnt);}}
}