题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
JAVA
import java.util.*; public class Main{ public static void main(String[] args){ Scanner scanner = new Scanner(System.in); while(scanner.hasNext()){ //链表节点个数 int num = scanner.nextInt(); //声明一个最后构造成功的链表 ListNode node = new ListNode(); node.next = null; //头插法构造倒置的链表 for(int i = 0;i<num;i++){ ListNode p = new ListNode(); int x = scanner.nextInt(); p.next = node.next; p.val = x; node.next = p; } int k = scanner.nextInt(); ListNode kthNode = getKthNode(node,k); System.out.println(kthNode.val); } } public static ListNode getKthNode(ListNode node,int k){ ListNode front = node; int j =0; //遍历找到需要被删除的那个节点 while(front.next != null && j<k){ j++; front = front.next; } return front; } } class ListNode{ public int val; public ListNode next; }