0 题目
输入一个链表,输出该链表中倒数第k个结点。
1 思路解析
方法:滑动窗口法
设滑动窗口大小为K
滑动窗口的性质:剩余点个数为K-1。滑窗后的返回点个数据为N-(K-1).
一般的解法:先遍历一遍该单链表,获取链表的总节点数 n,那么第 n-k+1 这个节点就是倒数第 k 个节点。所以第二次再遍历到第 n-k+1 这个节点即可。
我们可以借助滑窗的思想解决此问题:窗口的大小即为K,不断移动该窗口,直到该窗口右边界为NULL时不再移动,此时窗口中左边界处即为要找的点。图示如下:
解决思路:
(1)设置两个指针初始位置为head
(2)让第一个指针先移动K-1步。此时指针1和指针2步长相差为k,相当于确定滑动窗口大小。
(3)然后整个窗口滑动。滑动的终止条件是p的指向为空的时候,此时p2的指针位置就是我们要找的节点
2 代码示例
package com.dandan.builder.suanfa;
public class Solution1 {
public ListNode FindKthToTail(ListNode head,int k){
/*
*
k 如果 比我们的链表的长度还要大的话,我们直接返回None
k 如果小于链表的长度,我们可以定义两个变量,这两个变量中间间隔k
用两个指针做一个尺子,然后让尺子在跳跳,然后就会找到 第k 个结点
*
*/
// 鲁棒性:输入参数的检查
if(head == null || k <= 0){
return null;
}
//定义连个指针,第一个指针和第二个指针。两个指针都是从头开始
ListNode firstPoint = head;
ListNode secondPoint = head;
//首先让一个指针先开始移动,移动k-1步时,找到了一次滑动的子窗口。
for (int i = 0; i <k-1 ; i++) {
//如果当第一个指针走到null的话,说明K的长度已经超过链表的长度需要返回null。
//判断的时候在每一次指针往前走的时候判断。因为在最后一个节点时,节点指向null
if(firstPoint == null){
return null;
}
//第一个指针一直往前走
firstPoint=firstPoint.next;
}
//循环结束后firstPoint已经走到K的位置
//此时移动两个指针(移动步长)
//当第一个指针(先走的指针,窗口(步长)的尾端)指向为null的时候,说明不能在移动了
while(firstPoint.next != null){
firstPoint=firstPoint.next;
secondPoint = secondPoint.next;
}
//循环结束后secondPoint位置就是需要的倒数K个点
return secondPoint;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 6, 5, 6};
ListNode head = new ListNode(nums);
System.out.println(head);
ListNode res = (new Solution1()).FindKthToTail(head,3);
System.out.println(res);
}
}
public class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
//链表节点的构造函数
//使用arr为参数,创建一个链表,当前的ListNode为链表的头节点
public ListNode(int[] arr){
if(arr.length == 0 || arr == null){
throw new IllegalArgumentException("arr can not be empty");
}
this.val = arr[0];
ListNode cur = this;
for (int i = 1; i <arr.length ; i++) {
cur.next = new ListNode(arr[i]);
cur=cur.next;
}
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
ListNode cur = this;
while(cur != null){
res.append(cur.val + "->");
cur=cur.next;
}
res.append("NULL");
return res.toString();
}
}
测试结果如下:
3 代码优化(滑窗思想)
- 1、首先定义两个指向链表头的指针 pre 和 last;
- 2、先令pre指针指向第k节点;
- 3、然后两个指针同时向后移动,最后pre指向尾节点,而last指向的就是倒数第k个节点;
- 4、当k为零或节点为空返回null。
只用一次遍历
public ListNode FindKthToTail2(ListNode head, int k){
// 定义两个指针
ListNode pre = head;
ListNode last = head;
int i = 0;
for (; pre.next != null; i++) {
if(i >= k-1){
// 此时pre指针走了k-1步,后面两个指针一起向后遍历
last = last.next;
}
pre = pre.next;
}
// 考虑鲁棒性
return i < k-1 ? null : last;
}
代码继续优化
public ListNode FindKthToTail3(ListNode head, int k){
// 定义两个指针
ListNode pre ;
ListNode last;
for (pre=last=head; pre.next != null; pre = pre.next,k--) {
if(k<=1){
// 此时pre指针走了k-1步,后面两个指针一起向后遍历
last = last.next;
}
}
// 考虑鲁棒性
return k<=1 ? last : null;
}