File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments