Leetcode - Middle of the Linked List - Solution
Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Link Of the Problem:- https://leetcode.com/problems/middle-of-the-linked-list/description/
Solution:-
# Intuition
To Find the Middle Node of LinkedList.
# Approach
I have used TortoiseHare Method Here.
In this method, we move the slow pointer by one in every iteration and move the fast pointer by two.
# Complexity
- Time complexity: O(N/2)
- Space complexity: O(1)
# Code
```
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode *slow = head, *fast = head;
while(fast !=NULL && fast->next !=NULL)
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};
```
Like this blog and share this with your Friends.
Keep Learning, Keep Growing.
nice explanation.
ReplyDelete