mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-24 22:39:52 +03:00
Update solution for problem 876
This commit is contained in:
parent
e5dad3fa8d
commit
6975224e69
@ -1,19 +1,19 @@
|
|||||||
/**
|
// Function to find the middle node of a linked list
|
||||||
* Definition for singly-linked list.
|
// this contains the edge cases also
|
||||||
* struct ListNode {
|
struct ListNode* middleNode(struct ListNode* head) {
|
||||||
* int val;
|
// Check if the list is empty or has only one node
|
||||||
* struct ListNode *next;
|
if (head == NULL || head->next == NULL) {
|
||||||
* };
|
return 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;
|
|
||||||
}
|
}
|
||||||
return slow;
|
|
||||||
}
|
struct ListNode* fast = head;
|
||||||
|
struct ListNode* slow = head;
|
||||||
|
|
||||||
|
// 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; // Slow will be at the middle node
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user