mirror of
https://github.com/TheAlgorithms/C.git
synced 2026-09-23 15:34:20 +00:00
* feat:leetcode Delete the Middle Node of a Linked List solution (2095) * Update README.md * Update README.md * Update DIRECTORY.md Co-authored-by: David Leal <halfpacho@gmail.com>
39 lines
775 B
C
39 lines
775 B
C
/**
|
|
* Definition for singly-linked list.
|
|
* struct ListNode {
|
|
* int val;
|
|
* struct ListNode *next;
|
|
* };
|
|
*/
|
|
|
|
struct ListNode* deleteMiddle(struct ListNode* head)
|
|
{
|
|
if (head == NULL || head->next == NULL)
|
|
return NULL;
|
|
struct ListNode *fast, *slow, *prev;
|
|
int n = 0;
|
|
fast = head;
|
|
slow = head;
|
|
while (fast != NULL)
|
|
{
|
|
n = n + 1;
|
|
fast = fast->next;
|
|
}
|
|
fast = head;
|
|
while (fast->next != NULL && fast->next->next != NULL) // finds mid node
|
|
{
|
|
prev = slow;
|
|
slow = slow->next;
|
|
fast = fast->next->next;
|
|
}
|
|
if (n % 2 == 0)
|
|
{
|
|
prev = slow;
|
|
slow = slow->next;
|
|
prev->next = slow->next;
|
|
}
|
|
else
|
|
prev->next = slow->next;
|
|
return head;
|
|
}
|