题解 | #链表倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
/* for(int i = 0 ; i < n ; i ++) { if(i == 0) { root = new Node(sc.nextInt()) ; continue ; } t.next = new Node(sc.nextInt()) ; t = t.next ; } sc.nextLine() ; */ import java.util.* ; class Node { int val ; Node next ; Node(int val) { this.val = val ; } } public class Main{ public static void main(String...args) { Scanner sc = new Scanner(System.in) ; while(sc.hasNextLine()) { int n = sc.nextInt() ; sc.nextLine() ; Node root = null ; Node t = null ; String[] arr = sc.nextLine().split(" ") ; for(int i = 0 ; i < arr.length ; i ++) { int num = Integer.parseInt(arr[i]) ; if(i == 0) { root = new Node(num) ; t = root ; continue ; } t.next = new Node(num) ; t = t.next ; } int k = sc.nextInt() ; sc.nextLine() ; //=============================== if(k == 0) { System.out.println("0") ; } else { System.out.println(solu(root,k).val) ; } } } public static Node solu(Node root , int k) { Node fast = root ; int c = 0 ; //快指针先走k步 while(fast != null && c < k-1) { fast = fast.next ; c++ ; } //考虑链表长度小于k if(fast == null) { return null ; } //慢指针在原地 Node slow = root ; //快慢指针同时走,当快指针到达tail结点,那么慢指针刚好在第k个结点 while(fast.next != null) { fast = fast.next ; slow = slow.next ; } return slow ; } }
一个菜鸟的算法刷题记录 文章被收录于专栏
分享一个菜鸟的成长记录