Skip to content

Commit 2c7108c

Browse files
authored
Create 0876-Middle-of-the-Linked-List.cpp
1 parent fe5ecf7 commit 2c7108c

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
12+
class Solution {
13+
public:
14+
ListNode* middleNode(ListNode* head) {
15+
/*
16+
The slow and fast pointer algorithm is used to find the middle
17+
of a linked list by iterating through the list with a slow
18+
pointer that moves one step at a time and a fast pointer that
19+
moves two steps at a time. When the fast pointer reaches the
20+
end of the list, the slow pointer will be at the midpoint of the list.
21+
*/
22+
ListNode *slow_pointer = head, *fast_pointer = head;
23+
while (fast_pointer != NULL && fast_pointer->next != NULL) {
24+
slow_pointer = slow_pointer->next;
25+
fast_pointer = fast_pointer->next->next;
26+
}
27+
return slow_pointer;
28+
}
29+
};

0 commit comments

Comments
 (0)