题目:
题解:
一、构建链表+顺序访问
- 顺序构建链表
- 获取链表长度n
- 倒数k = 顺序的 n-k
- 依次遍历链表元素获取第 n-k 个节点值
public int getLastKNode(List<Integer> list, int k) {
int length = 0;
ListNode temp = new ListNode();
ListNode head = temp;
for (Integer value : list) {
ListNode listNode = new ListNode(value);
temp.next = listNode;
temp = listNode;
length++;
}
int index = length - k;
head = head.next;
while (index > 0) {
head = head.next;
index--;
}
return head.value;
}
时间复杂度:O(2n)
二、快慢指针
- 快指针先走k个节点
- 当快指针走完第k个节点,慢指针开始走
- 当快指针走到链表结尾,慢指针对应的节点就是倒数第k个节点
public int getLastKNode(List<Integer> list, int k) {
ListNode temp = new ListNode();
ListNode slow = null;
for (int i = 0; i < list.size(); i++) {
ListNode listNode = new ListNode(list.get(i));
temp.next = listNode;
temp = listNode;
if (i == 0) {
slow = listNode;
}
if (i > k-1) {
slow = slow.next;
}
}
return slow.value;
}
时间复杂度:O(n)