题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
//正序构建链表;采用尾插法
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNext()){
//此处只能用hasNext(),判断是否有输入
//用hasNextLine()出错,判断是否有输入字符串
int num = in.nextInt();
ListNode tail = new ListNode(in.nextInt(), null);
ListNode head = new ListNode();
head.next = tail;
for(int i =1; i<num; i++){
//尾插法
ListNode p = new ListNode(in.nextInt(), null);
tail.next = p;
tail = p;
}//for_i,构建链表
head = head.next;//
int k = in.nextInt();
ListNode n = new ListNode();
if(k <= 0 || k > num ){
System.out.println(0);
continue;
}
ListNode fast = head , slow = head;
for(int i = 0; i<k; i++){
//if(fast==null) return fast;
fast = fast.next;
}//此时fast指向[k]元素,0(slow),1,2...k(fast)
while(fast!=null ){
fast = fast.next;
slow = slow.next;
}//while_fast,当fast为空时,slow指向倒数第k个元素,即0(fast),-1,-2,...-k(slow)
System.out.println(slow.value);
//System.out.print("jieshu");
}//while
}
}//Main
class ListNode{
int value;
ListNode next;
public ListNode(int v, ListNode p){
this.value = v;
this.next = p;
}
public ListNode(){
}
}
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNext()){
//此处只能用hasNext(),判断是否有输入
//用hasNextLine()出错,判断是否有输入字符串
int num = in.nextInt();
ListNode tail = new ListNode(in.nextInt(), null);
ListNode head = new ListNode();
head.next = tail;
for(int i =1; i<num; i++){
//尾插法
ListNode p = new ListNode(in.nextInt(), null);
tail.next = p;
tail = p;
}//for_i,构建链表
head = head.next;//
int k = in.nextInt();
ListNode n = new ListNode();
if(k <= 0 || k > num ){
System.out.println(0);
continue;
}
ListNode fast = head , slow = head;
for(int i = 0; i<k; i++){
//if(fast==null) return fast;
fast = fast.next;
}//此时fast指向[k]元素,0(slow),1,2...k(fast)
while(fast!=null ){
fast = fast.next;
slow = slow.next;
}//while_fast,当fast为空时,slow指向倒数第k个元素,即0(fast),-1,-2,...-k(slow)
System.out.println(slow.value);
//System.out.print("jieshu");
}//while
}
}//Main
class ListNode{
int value;
ListNode next;
public ListNode(int v, ListNode p){
this.value = v;
this.next = p;
}
public ListNode(){
}
}

