题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
import java.util.Scanner; public class Main { public static class ListNode{ int val; ListNode next; ListNode(int val){ this.val=val; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while(in.hasNext()){ int n=in.nextInt(); ListNode h=new ListNode(in.nextInt()); ListNode p=h; for(int i=1;i<n;i++){ p.next=new ListNode(in.nextInt()); p=p.next; } int k=in.nextInt(); System.out.println(fromHead(h,k)); } } public static int fromHead(ListNode h,int k){ ListNode q=h; int count=1;//注意初始是1,因为链表不为空 while(q.next!=null){ count++; q=q.next; } if(count==1){ return q.val; } q=h; for(int i=1;i<=count ;i++){ if(i==count+1-k){ return q.val; } q=q.next; } return 0; } }