题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
int num = sc.nextInt();
//构建带有头节点的链表
ListNode head = new ListNode();
ListNode tmp = head;//head不移动,利用辅助变量来遍历
for (int i = 0; i < num; i++) {
ListNode node = new ListNode(sc.nextInt());
tmp.next = node;
tmp = tmp.next;//tmp后移
}
int k = sc.nextInt();
if (getKthNodeFromEnd(head, k) != null) {
System.out.println(getKthNodeFromEnd(head, k).val);
} else System.out.println(0);
}
}
public static ListNode getKthNodeFromEnd(ListNode head, int k) {//获取链表倒数第k个节点的方法
int len = getLength(head);//题目要求构建后要忘记链表长度,自己重新获取链表长度
if (len == 0 || k > len) {//空链表或者k超过链表长度,返回null
return null;
}
ListNode tmp = head;
for (int i = 0; i < len - k + 1; i++) {//从head-0开始,正数第n-k+1个,就是倒数第k个
tmp = tmp.next;
}
return tmp;
}
public static int getLength(ListNode head) {//传入链表头节点,获取该链表长度
// if (head.next == null) {//空链表
// return 0;
// }
int length = 0;
ListNode tmp = head.next;//定义辅助变量用于遍历
while (tmp != null) {
length++;
tmp = tmp.next;//指针后移
}
return length;
}
}
class ListNode {//定义节点
int val;
ListNode next;
ListNode(){//默认空构造器
};
ListNode(int val) {//构造器
this.val = val;
next = null;
}
}