class LNode
{
public LNode next;
public int data;
}
/*找出倒数第k个元素,只遍历一遍*/
class Kk
{
private static LNode head = new LNode();;
private static LNode node;
private static LNode tail;
private static LNode fast;
private static LNode slow;
private static int index;
private static int k;
public static void main(String[] args){
int[] nums = {1,2,3,4,5,6,7,8,9,10};
head.data = nums[0];
tail = head;
createLine(nums);
printLine();
//假设要找的倒数K为4,也就是7
//让fast先走K步,随后slow跟上,同步后移,当fast到达最后,slow的位置就是倒数K
k=4;
fast = head;
for (int i=0;i<4 ;i++ )
{
fast = fast.next;
System.out.println("fast开始:"+fast.data);
}
//当fast到达第K个元素,slow就从第一个元素开始
slow = head.next;
while (fast!=null&&fast.next!=null)
{
fast = fast.next;
System.out.println("fast="+fast.data);
slow = slow.next;
System.out.println("slow="+slow.data);
}
System.out.println("链表的倒数第"+k+"个元素是:"+slow.data);
}
private static void createLine(int[] nums){
while (index<10)
{
node = new LNode();
tail.next = node;
node.data = nums[index];
node.next = null;
tail = node;
index ++;
}
}
private static void printLine(){
node = head;
while(node!=null&&node.next!=null){
node = node.next;
System.out.println(node.data);
}
}
}