题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
双指针法 让fst指针先走k步 然后snd再跟着走 等到fst走到结尾 snd指针的值就是第k个值
#华为笔试#
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
ListNode head = new ListNode();
ListNode cur = head;
int n = in.nextInt();
while (n-- > 0) {
ListNode node = new ListNode(in.nextInt());
cur.next = node;
cur = node;
}
ListNode fst = head.next, snd = head.next;
int k = in.nextInt();
while (k-- > 0 && fst != null) {
fst = fst.next;
}
while (fst != null) {
fst = fst.next;
snd = snd.next;
}
System.out.println(snd.val);
}
}
}
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
#华为笔试#

查看14道真题和解析