转自:程序员小灰
链接:https://mp.weixin.qq.com/s/kKyghET5xmu4PoNPVWsSvQ
原文非常好,有解题思路,抄录只是为了方便自己学习
package com.example.demo;
public class GetReciprocaIndex {
//获取一个链表上倒数第n个节点
static class NodeLink{
NodeLink next;
int value;
NodeLink(int date){
this.value = date;
next = null;
}
}
public static int getN(NodeLink head , int n){
//利用两个指针来遍历链表,两个链表相隔n个,当第二指针指到最后一个节点时,前一个指针就是返回的节点
NodeLink pre = head;
NodeLink last = head;
for (int i=1;i<n;i++){
last = last.next;
if (last==null){
break;
}
}
while(last.next!=null){
pre = pre.next;
last = last.next;
}
return pre.value;
}
public static void main(String[] args) {
NodeLink node1 = new NodeLink(1);
NodeLink node2 = new NodeLink(2);
NodeLink node3 = new NodeLink(3);
NodeLink node4 = new NodeLink(4);
NodeLink node5 = new NodeLink(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
int value = getN(node1,5);
System.out.println(value);
}
}