题目链接: https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/

题目解析
- 遍历的方式计算出链表的长度
n
,然后在遍历到第n-k
的位置即可。
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
int n = 0;
ListNode node = null;
for (node = head; node != null; node = node.next) {
n++;
}
for (node = head; n > k; n--) {
node = node.next;
}
return node;
}
}
复杂度分析
空间复杂度: O(1)。
时间复杂度: O(N)。
-
利用快慢指针,遍历一次即可。
fast
指针比slow
指针慢k
步,当fast
到尾的时候,slow
的就是需要的值。
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode fast = head;
ListNode slow = head;while (fast != null && k > 0) { fast = fast.next; k--; } while (fast != null) { fast = fast.next; slow = slow.next; } return slow;
}
}
复杂度分析
空间复杂度: O(1)。
时间复杂度: O(N)。
网友评论