一.实现思路
转变一下思路,因为单链表是只能正向遍历的,所以遍历的次数为(链表长度-N),拿到的节点即为倒数第N个节点
二.代码实现
//拿到节点的个数
public int getNodeNum(Node head) {
if (head.next == null) {
return 0;
}
int count = 0;
Node cur = head.next;
while (cur != null) {
count++;
cur = cur.next;
}
return count;
}
//拿到倒数第index个节点,换一种思路,其实就是正向遍历到(节点个数-index)
public Node getLastIndex(Node head, int index) {
if (head.next == null) {
return null;
}
Node cur = head;
for (int i = 0; i <= getNodeNum(head) - index; i++) {
cur = cur.next;
}
return cur;
}