难度系数 ⭐
时间限制 C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
题目内容 输入一个链表,输出该链表中倒数第k个结点。
思路 首先遍历一下链表,记录链表长度。然后倒数第k个节点,即第len-k+1个节点。
package nowcoder;
public class No16 {
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static ListNode FindKthToTail(ListNode head, int k) {
if (head == null) return null;
ListNode cur = head;
int len = 0;
while (cur != null){
len++;
cur = cur.next;
}
if (len < k) return null;
else {
cur = head;
for (int i = 1; i < len - k + 1; i++)
cur = cur.next;
return cur;
}
}
public static void main(String[] args){
ListNode node = new ListNode(1);
node.next = new ListNode(2);
node.next.next = new ListNode(3);
node.next.next.next = new ListNode(4);
node.next.next.next.next = new ListNode(5);
System.out.print(FindKthToTail(node, 5).val);
}
}