//思路大家都知道,需要注意的一点就是,如果按照常规的快慢指针的思路,当有偶数个节点时,输出的中间节点是后一个,而不是前一个,所以需要稍微处理一下。
public static Node searchMiddleNode(Node head) {
if (head == null || head.next == null)
return head;
// 一般查找问题都是两个指向头节点的指针(快慢指针)共同移动。
int length = getListLength(head);
Node fast = head;
Node slow = head;
Node temp = slow;//如果有两个中间节点,取前一个
while (fast != null && fast.next != null) {
temp = slow;
fast = fast.next.next;
slow = slow.next;
}
temp.next = null;
slow.next = null;
//System.out.print("temp.value: " + temp.value + " slow.value: " + slow.value);
if(length % 2 != 0)
return slow;
else
return temp;
}
if(head.next == null || head.next.next == null)
return head;
node pre = head;
node cur = head.next.next;
while(cur.next != null && cur.next.next != null) { //每增加两个节点,中节点后移一个
pre = pre.next;
cur = cur.next.next;
}
return pre.val;