Skip to content

Commit d71120a

Browse files
committed
c: add 0876-middle-of-the-linked-list
1 parent c5ec43f commit d71120a

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

c/0876-middle-of-the-linked-list.c

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Given the head of a singly linked list, return the middle node of the linked
3+
* list.
4+
*
5+
* If there are two middle nodes, return the second middle node.
6+
*
7+
* Constraints:
8+
*
9+
* The number of nodes in the list is in the range [1, 100].
10+
* 1 <= Node.val <= 100
11+
*
12+
* Definition for singly-linked list.
13+
* struct ListNode {
14+
* int val;
15+
* struct ListNode *next;
16+
* };
17+
*
18+
* Space = O(1)
19+
* Time = O(n)
20+
*/
21+
22+
struct ListNode* middleNode(struct ListNode* head){
23+
struct ListNode* slow = head;
24+
struct ListNode* fast = head;
25+
26+
while (fast && fast->next) {
27+
slow = slow->next;
28+
fast = fast->next->next;
29+
}
30+
31+
return slow;
32+
}

0 commit comments

Comments
 (0)