【力扣面试】面试题 02.02. 返回倒数第 k 个节点
题目
实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。
注意:本题相对原题稍作改动
示例:
输入: 1->2->3->4->5 和 k = 2
输出: 4
说明:
给定的 k 保证是有效的。
解题思路
1、先得到链表长度,count
2、再count = count - k + 1; //此时的count就是倒数第k个,进行链表遍历
class Solution {
public int kthToLast(ListNode head, int k) {
ListNode temp = head;
int count = 0;
while (temp != null) { //先得到链表长度,count
count++;
temp = temp.next;
}
count = count - k + 1; //此时的count就是倒数第k个
int i = 1;
temp = head;
while (i < count) {
temp = temp.next;
i++;
}
return temp.val;
}
}