题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
思路:
1.构建节点类
2.根据输入的数据形成链表
3.寻找倒数第K个节点:
采用快慢指针:(1)先让快指针走K步(2)同时让快慢指针一起走,当快指针指向为空时,此时的慢指针指向目标节点。
4.注意点:需要注意到K<1的情况
import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.Buffer; /** * @author m * @Description 输出单向链表中倒数第k个结点 * 思路:快慢指针法: * 1.让快指针先走k步 * 2.快慢指针同时开始走,当快指针=null时,慢指针指向目标 * @creat 2021-07-22 */ public class HJ51 { /** * 节点类 */ public static class Node{ Node next; int val; Node(int val){ this.val=val; this.next=null; } } public static void main(String[] args) throws Exception{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String s; while((s = bf.readLine())!=null){ int N = Integer.parseInt(s);//节点个数 String[] str = bf.readLine().split(" "); int K = Integer.parseInt(bf.readLine()); //形成链表: Node head = new Node(Integer.parseInt(str[0])); Node temp = head; for(int i=1;i<str.length;i++){ Node node = new Node(Integer.parseInt(str[i])); temp.next = node; temp = temp.next; } if(K==0) System.out.println(0); else{ int res = findK(head, K); System.out.println(res); } } } static int findK(Node head,int K){ Node fast = head; Node slow = head; for(int i=0;i<K;i++){ fast = fast.next; } // while(fast != null){ fast = fast.next; slow = slow.next; } //此时slow指向第K个节点 return slow.val; } }