解法一:暴力求解法
class Solution {
public ListNode middleNode(ListNode head) {
ListNode node = head;
int size = 0;
while(node != null) {
size++;
node = node.next;
}
for(int i = 0; i < size/2; i++) {
head = head.next;
}
return head;
}
}
运行截图:
解法二、快慢指针法
class Solution {
public ListNode middleNode(ListNode head) {
ListNode low = head,fast = head;
while(fast != null && fast.next != null) {
low = low.next;
fast = fast.next.next;
}
return low;
}
}
运行截图: