查找单链表的倒数第K个节点,要求只能遍历一次链表
- 定义两个前后节点forward和backward
- 先让forward走 k 步,再让forward和backward一起走,当forward走到空,此时backward就走到了倒数第k步
class ListNode{
int data;
ListNode next;
}
public class Link{
public static void FindTailK(ListNode first,int k){
ListNode forward = first;
ListNode backward = first;
while(k-- != 0){
forward = forward.next;
}
while(forward != null){
forward = forward.next;
backward = backward.next;
}
System.out.println(backward.data);
}
public static void main(String[] args) {
ListNode n1 = new ListNode();
ListNode n2 &