<span style="color:rgb(51,51,51); font-family:Arial; font-size:14.399999618530273px; line-height:26px">题目:输入一个单向链表,输出该链表中倒数第k个结点。链表的倒数第0个结点为链表的尾指针。</span><br style="color:rgb(51,51,51); font-family:Arial; font-size:14.399999618530273px; line-height:26px" />
import java.util.*;
class Node{
Node next;
int data;
public Node(int data){
this.data=data;
}
}
public class Main{
public static Node findElement(Node node,int k){
if(k<0||node==null){return null;}
Node n1=node;
Node n2=node;
for(int i=0;i<k+1;i++){
n1=n1.next;
if(n1==null){
return null;
}
}
while(n1!=null){
n1=n1.next;
n2=n2.next;
}
return n2;
}
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
//Node head=new Node(sc.nextInt());
Node[] n=new Node[num];
for(int i=0;i<num;i++){
n[i]=new Node(sc.nextInt());
if(i==0){
n[0].next=n[1];
}else{
n[i-1].next=n[i];
}
}
int k=sc.nextInt();
Node result=findElement(n[0], k);
System.out.println(result.data);
}
}