diff --git a/problems/middle-of-the-linked-list.cpp b/problems/middle-of-the-linked-list.cpp new file mode 100644 index 0000000..847d914 --- /dev/null +++ b/problems/middle-of-the-linked-list.cpp @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* middleNode(ListNode* head) { + auto slow = head; + auto fast = head ? head->next : nullptr; + + while (fast != nullptr) { + slow = slow->next; + fast = fast->next; + if (fast) { + fast = fast->next; + } + } + + return slow; + } +};