题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
这是一个没有灵魂的双指针法
测试用例里倒数第0个是0,我就写成0了
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); while(sc.hasNext()){ int num=sc.nextInt(); ListNode head=new ListNode(sc.nextInt()); ListNode cur=head; for(int i=1;i<num;i++){ ListNode node=new ListNode(sc.nextInt()); cur.next=node; cur=cur.next; } int k=sc.nextInt(); ListNode cur2=head; ListNode cur3=head; int i=1; if(k>num||k<=0){ System.out.println(0); } else{ while(i<k){ cur2=cur2.next; i++; } while(cur2.next!=null){ cur2=cur2.next; cur3=cur3.next; } System.out.println(cur3.val); } } } } class ListNode{ int val; ListNode next; ListNode(int val){ this.val=val; } }