两种方法:时间复杂度都为O(N)
1.转为数组保存,求出总长度的一半 空间复杂度O(n)
2.快慢指针法,输出慢指针 空间复杂度O(1)
JAVA
class Solution { public ListNode middleNode(ListNode head) { ListNode[] res = new ListNode[100]; int i = 0; while(head != null){ res[i++] = head; head = head.next; } return res[i/2]; } }
class Solution { public ListNode middleNode(ListNode head) { ListNode fast = head; ListNode slow = head; while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; } return slow; } }
Python3
class Solution: def middleNode(self, head: ListNode) -> ListNode: res = [] while head: res.append(head) head = head.next return res[len(res)//2]
class Solution: def middleNode(self, head: ListNode) -> ListNode: slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow