-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
17 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,19 @@ | ||
/** | ||
* Definition for singly-linked list. | ||
* struct ListNode { | ||
* int val; | ||
* struct ListNode *next; | ||
* }; | ||
*/ | ||
// Function to find the middle node of a linked list | ||
// this contains the edge cases also | ||
struct ListNode* middleNode(struct ListNode* head) { | ||
// Check if the list is empty or has only one node | ||
if (head == NULL || head->next == NULL) { | ||
return head; | ||
} | ||
|
||
struct ListNode* fast = head; | ||
struct ListNode* slow = head; | ||
|
||
struct ListNode *middleNode(struct ListNode *head) | ||
{ | ||
struct ListNode *fast, *slow; | ||
fast = slow = head; | ||
while (fast && fast->next) | ||
{ | ||
slow = slow->next; | ||
fast = fast->next->next; | ||
// Use two pointers to find the middle node | ||
while (fast != NULL && fast->next != NULL) { | ||
fast = fast->next->next; // Move fast pointer two steps | ||
slow = slow->next; // Move slow pointer one step | ||
} | ||
return slow; | ||
} | ||
|
||
return slow; // Slow will be at the middle node | ||
} |