版权声明:be the one ~you will be the one~~ https://blog.csdn.net/Hqxcsdn/article/details/88184888
快慢指针的经典题型
/**
*
*/
/***
* @author 18071
* @Date 2019年3月5日
* 功能:链表的倒数k个节点
* 思路:快慢指针法
***/
public class test {
public static void main(String args[]) {
Solution s= new Solution() ;
ListNode root =new ListNode(1);
root.next=new ListNode(2);
root.next.next= new ListNode(3);
root.next.next.next=new ListNode(4);
root.next.next.next.next=new ListNode(5);
int k=5;
System.out.println( s.findK(root, k));
}
}
class Solution {
public int findK(ListNode list,int k) {
if(list==null) {
return 0;
}
ListNode fast=list;
ListNode slow=list;
while(fast.next!=null&&k>0) {
k--;
fast=fast.next;
}
while(fast.next!=null) {
fast=fast.next;
slow=slow.next;
}
return slow.value;
}
}
class ListNode{
int value ;
ListNode next;
ListNode(int value){
this.value=value;
}
}