1. First traverse the entire list, obtains the length of the list, identify an intermediate node during the cycle
public class Solution {
public ListNode middleNode(ListNode head) {
int len=0;
for(ListNode cur=head;cur!=null;cur=cur.next)
len++;//遍历算出链表长度
ListNode node=head;
for(int i=0;i<len/2;i++)
node=node.next;
return node;
}
}
2. Use speed pointers define two references, FAST pointer moving twice, slow pointer a step, until the stop fast.next = null, i.e. an intermediate node
public class Solution {
public ListNode middleNode(ListNode head) {
ListNode fast=head;
ListNode slow=head;
while(fast!=null){
fast=fast.next;
if(fast==null){
break;
}//因为fast每次走两步,有可能走一步时就到了最后(奇数节点时)
slow=slow.next;
fast=fast.next;
}
return slow;
}
}