|
| 1 | +# Problem: Middle of the Linked List |
| 2 | + |
| 3 | +LeetCode problem: [876. Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/). |
| 4 | + |
| 5 | +Given the head of a singly linked list, write a method to return the middle node of the linked list. |
| 6 | + |
| 7 | +If the total number of nodes in the linked list is even, return the second middle node. |
| 8 | + |
| 9 | +## Examples |
| 10 | + |
| 11 | +Example 1: |
| 12 | + |
| 13 | +```plaintext |
| 14 | +Input: 1 ──▶ 2 ──▶ 3 ──▶ 4 ──▶ 5 ──▶ null |
| 15 | +Output: 3 |
| 16 | +``` |
| 17 | + |
| 18 | +Example 2: |
| 19 | + |
| 20 | +```plaintext |
| 21 | +Input: 1 ──▶ 2 ──▶ 3 ──▶ 4 ──▶ 5 ──▶ 6 ──▶ null |
| 22 | +Output: 4 |
| 23 | +``` |
| 24 | + |
| 25 | +Example 3: |
| 26 | + |
| 27 | +```plaintext |
| 28 | +Input: 1 ──▶ 2 ──▶ 3 ──▶ 4 ──▶ 5 ──▶ 6 ──▶ 7 ──▶ null |
| 29 | +Output: 4 |
| 30 | +``` |
| 31 | + |
| 32 | +## Solution 1 |
| 33 | + |
| 34 | +First calculates the total length of the list by traversing it, then iterates through the first half of the list to locate the middle node, which is then returned. |
| 35 | + |
| 36 | +Complexity analysis: |
| 37 | + |
| 38 | +- Time complexity: O(N) - two-pass algorithm |
| 39 | +- Space complexity: O(1) |
| 40 | + |
| 41 | +```python |
| 42 | +class ListNode: |
| 43 | + def __init__(self, val=0, next=None): |
| 44 | + self.val = val |
| 45 | + self.next = next |
| 46 | + |
| 47 | +def middleNode(head: Optional[ListNode]) -> Optional[ListNode]: |
| 48 | + length = 0 |
| 49 | + current = head |
| 50 | + while current is not None: |
| 51 | + length += 1 |
| 52 | + current = current.next |
| 53 | + |
| 54 | + middle = head |
| 55 | + for i in range(length // 2): |
| 56 | + middle = middle.next |
| 57 | + |
| 58 | + return middle |
| 59 | +``` |
| 60 | + |
| 61 | +## Solution 2 |
| 62 | + |
| 63 | +Using two pointers starting at the beginning of the linked list: |
| 64 | + |
| 65 | +- The slow pointer moves one node at a time. |
| 66 | +- The fast pointer moves two nodes at a time. |
| 67 | + |
| 68 | +When the fast pointer reaches the end of the linked list, the slow pointer will be positioned at the middle of the list. |
| 69 | + |
| 70 | +Complexity analysis: |
| 71 | + |
| 72 | +- Time complexity: O(N) - one-pass algorithm |
| 73 | +- Space complexity: O(1) |
| 74 | + |
| 75 | +```python |
| 76 | +class ListNode: |
| 77 | + def __init__(self, val=0, next=None): |
| 78 | + self.val = val |
| 79 | + self.next = next |
| 80 | + |
| 81 | +def middleNode(head: Optional[ListNode]) -> Optional[ListNode]: |
| 82 | + fast = head |
| 83 | + slow = head |
| 84 | + |
| 85 | + while fast is not None and fast.next is not None: |
| 86 | + fast = fast.next.next |
| 87 | + slow = slow.next |
| 88 | + |
| 89 | + return slow |
| 90 | +``` |
0 commit comments