链表找中间值,如果是偶数,返回中间第二个值
整体思想:使两个结点走的顺序为:* & * 一个周期
1.判断头结点是否为空,如果为空,返回null
2.设置两个结点back,front,使之都为头结点,
3.循环当front不为null时
1)先走front=front.next,再判断front是否为空,为空直接返回
2)让back=back.next,再让front=front.next(这里可以不用判断back是否为空,因为如果front在back前面,front为空back一定为空)
4.最后,返回back,back为中间结点
public static Node middleNode(Node head){
if(head==null){
return null;
}
Node back=head;
Node front=head;
while(front!=null){
front=front.next;
if(front==null){
return null;
}
back=back.next;
front=front.next;
}
return back;
}