Java写题解的第5天 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
解题思路:使用快慢指针,令快指针先指向头节点,再走k个位置,再令慢指针指向头节点,同时先后移动直到快指针指向null;
注:由于本题的输入已知了链表的长度,因此也可以在建立好链表之后直接移动到n-k的位置;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { int len = sc.nextInt(); ListNode pHead = new ListNode(sc.nextInt()); ListNode build = pHead; for (int i = 1; i < len; i++) { ListNode newNode = new ListNode(sc.nextInt()); build.next = newNode; build = newNode; } int k = sc.nextInt(); if (k == 0 || k > len) { System.out.println(0); } else { ListNode fast = pHead; for (int i = 0; i < k; i++) { fast = fast.next; } ListNode slow = pHead; while (fast != null) { slow = slow.next; fast = fast.next; } System.out.println(slow.val); } } } } class ListNode { int val; ListNode next; public ListNode() { } public ListNode(int val) { this.val = val; } public ListNode(int val, ListNode next) { this.val = val; this.next = next; } }