题目1517:链表中倒数第k个结点
经典的题目,关键是corner case
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class S15 {
public static void main(String[] args) throws FileNotFoundException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("in.in"));
System.setIn(in);
Scanner cin = new Scanner(System.in);
while (cin.hasNextInt()) {
int n = cin.nextInt();
int k = cin.nextInt();
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
for(int i=0; i<n; i++){
cur.next = new ListNode(cin.nextInt());
cur = cur.next;
}
getLastKth(dummy, k);
}
}
public static void getLastKth(ListNode dummy, int k){
ListNode head = dummy.next;
ListNode probe = head;
int i;
for(i=0; i<k; i++){
if(probe != null){
probe = probe.next;
}else{
break;
}
}
if(i != k){
System.out.println("NULL");
return;
}
ListNode cur = head;
while(probe != null){
probe = probe.next;
cur = cur.next;
}
if(cur != null){
System.out.println(cur.val);
}else{
System.out.println("NULL");
}
}
static class ListNode{
int val;
ListNode next;
public ListNode(int val){
this.val = val;
this.next = null;
}
}
}