题目链接:点击打开链接
题目1517:链表中倒数第k个结点import java.util.*;
import java.io.*;
public class Main {
public static void main(String []args){
Scanner cin = new Scanner(new InputStreamReader(System.in));
PrintWriter cout = new PrintWriter(System.out) ;
while(cin.hasNext()){
new Solve(cin.nextInt() , cin.nextInt() ).solve(cin , cout) ;
}
cout.flush() ;
cout.close();
}
}
class Node{
int val ;
Node next ;
Node(int val){
this.val = val ;
next = null ;
}
}
class Solve{
Node head = null ;
int n , k ;
Solve(int n , int k){
this.n = n ;
this.k = k ;
}
void solve(Scanner cin , PrintWriter cout){
if(n < k || n == 0 || k== 0){
while(n-- > 0) cin.next() ;
cout.println("NULL");
return ;
}
head = new Node(cin.nextInt()) ; //建立链表
Node now = head ;
for(int i = 1 ; i< n ; i++){
now.next = new Node(cin.nextInt()) ;
now = now.next ;
}
Node first = head ; //让第一个指针先向前走k步,当第一个指针到链尾时,第二个指针指向倒数第k个元素
for(int i =1 ; i<= k ; i++)
first = first.next ;
Node second = head ;
while(first != null){
first = first.next ;
second = second.next ;
}
cout.println(second.val);
}
}