题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
import java.util.*;
public class Main {
public static class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
int n = Integer.valueOf(scan.nextLine().trim());
String[] nums = scan.nextLine().split(" ");
int k = Integer.valueOf(scan.nextLine().trim());
ListNode head = createList(nums);
find(head, k);
}
}
// 自定义一个函数,实现链表的创建
public static ListNode createList(String[] nums) {
ListNode head = new ListNode(1);
ListNode node = new ListNode(1);
for (int i = 0; i < nums.length; i++) {
if (i == 0) {
head = new ListNode(Integer.valueOf(nums[i]));
node = head;
continue;
}
node.next = new ListNode(Integer.valueOf(nums[i]));
node = node.next;
}
node.next = null;
return head;
}
// 自定义一个函数,找到链表的倒数第 k 个节点
public static void find(ListNode head, int k) {
ListNode node = head;
int len = 0;
while (null != node) {
len++;
node = node.next;
}
int ans = 0;
node = head;
for (int i = 1; i <= len - k + 1; i++) {
ans = node.val;
node = node.next;
}
System.out.println(ans);
}
}