Middle of the Linked List
LeetCode 876 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Slow / fast pointers.
நான் Middle of the Linked List (LeetCode 876) ஐ இப்படித் தீர்த்தேன் — Basics பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Move one pointer a step at a time and another two steps at a time. When the fast pointer runs off the end, the slow one is in the middle.
Approach
- 1
slow = fast = head.
- 2
While fast and fast.next: slow one step, fast two.
- 3
Return slow (the second middle for even lengths).
நான் எப்படித் தீர்த்தேன்
Tortoise and harePythonO(n) time · O(1) space
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow =fast= head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slowMiddle of the Linked List — அடிக்கடி கேட்கப்படும் கேள்விகள்
Middle of the Linked List பின்னாலுள்ள intuition என்ன?
Move one pointer a step at a time and another two steps at a time. When the fast pointer runs off the end, the slow one is in the middle.
Middle of the Linked List (LeetCode 876) ஐ எப்படித் தீர்ப்பது?
1. slow = fast = head. 2. While fast and fast.next: slow one step, fast two. 3. Return slow (the second middle for even lengths).
Middle of the Linked List இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(1). (Accepted approach: Tortoise and hare.)
Middle of the Linked List இல் பொதுவான தவறுகள் என்ன?
The loop condition decides first vs second middle.