题目
输入一个链表,输出该链表中倒数第k个结点。
知识点
链表,双指针
思路
解法一、先遍历一遍链表得到链表结点数n,由n-k得从前往后数结点位置num,再遍历一遍得到结点。
解法二、通过快慢指针,快指针先遍历结点,与慢指针拉开k个结点差,再同时遍历,直到fast快指针=null,此时慢指针为倒数第k个结点。
代码
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
int n=0;
public ListNode FindKthToTail(ListNode head,int k) {
ListNode root = head;
while(root!=null){
n++;
root = root.next;
}
int x = n-k;
if(x<0) return null;
for(int i=0;i<x;i++){
head = head.next;
}return head;
}
}
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
int n=0;
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null||k<0) return null;
ListNode fast = head,slow = head;
while(k>=1){
if(fast!=null) fast=fast.next;
else return null;
k--;
}
while(fast!=null){
fast=fast.next;
slow=slow.next;
}return slow;
}
}