单向链表倒数第n项思路

版权声明:本文为博主原创文章,转载希望能注明出处,感谢。 https://blog.csdn.net/u010126792/article/details/82498601

算法很简单,只做记录用:

倒数第n项的求法很简单,只需要两个相差n-1的链表指针一直向前走,当前面的指针的next为null时,后面走的慢的指针正好是倒数第n个。

public static int findNode(Node node) {
		if (node == null || node.next == null) {
			return -1;
		}
		if (node.next.next == null) {
			return node.index;
		}
		Node first = node.next;
		Node second = node;
		while(first.next != null) {
			first = first.next;
			second = second.next;
		}
		
		return second.index;
		
	}

class Node{
    int index;
    Node next;
}

猜你喜欢

转载自blog.csdn.net/u010126792/article/details/82498601