题目
输入一个链表,输出该链表中倒数第K个节点,例如一个链表有6个结点,从头结点开始它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个结点是值为4的结点。
解决方案
我们可以定义两个指针。第一个指针从链表的头指针开始遍历向前走k-1,第二个指针保持不动,从第k步开始,第二个指针也开始从链表的头指针开始遍历。
由于两个指针的距离保持在k-1,当第一个(走在前面的)指针到达链表的尾结点时,第二个指针(走在后面的)指针正好是倒数第k个结点。
定义链表
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
public static void main(String[] args) {
ListNode head = new ListNode(0);
ListNode temp = head;
//模拟一个链表
for (int i = 1; i < 10; i++) {
temp.next = new ListNode(i);
temp = temp.next;
}
ListNode result = Solution.countdownKth(head, 2);
System.out.println(result.val);
}
public static ListNode countdownKth(ListNode head, int k) {
ListNode ahead = head;
ListNode behind = null;
for (int i = 0; i < k - 1; i++) {
//快指针
ahead = ahead.next;
}
//慢指针从头开始
behind = head;
while (ahead.next != null) {
//快指针达到终点的时候,慢指针指向的就是倒数第K个节点
ahead = ahead.next;
behind = behind.next;
}
return behind;
}
}