forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#2055 from andrewmustea/add_876-middle-…
…of-the-linked-list.c create 0876-middle-of-the-linked-list.c
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 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 |
---|---|---|
@@ -0,0 +1,32 @@ | ||
/** | ||
* 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. | ||
* | ||
* Constraints: | ||
* | ||
* The number of nodes in the list is in the range [1, 100]. | ||
* 1 <= Node.val <= 100 | ||
* | ||
* Definition for singly-linked list. | ||
* struct ListNode { | ||
* int val; | ||
* struct ListNode *next; | ||
* }; | ||
* | ||
* Space = O(1) | ||
* Time = O(n) | ||
*/ | ||
|
||
struct ListNode* middleNode(struct ListNode* head){ | ||
struct ListNode* slow = head; | ||
struct ListNode* fast = head; | ||
|
||
while (fast && fast->next) { | ||
slow = slow->next; | ||
fast = fast->next->next; | ||
} | ||
|
||
return slow; | ||
} |