-
Notifications
You must be signed in to change notification settings - Fork 0
/
middle_node.cpp
68 lines (63 loc) · 1.67 KB
/
middle_node.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* =====================================================================================
*
* Filename: middle_node.cpp
*
* Description: 876. Middle of the Linked List.
* https://leetcode.com/problems/middle-of-the-linked-list/
*
* Version: 1.0
* Created: 02/16/2023 17:53:52
* Revision: none
* Compiler: gcc
*
* Author: [email protected]
* Organization:
*
* =====================================================================================
*/
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
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) {}
static ListNode* convert(const std::vector<int>& nums) {
ListNode dummy;
ListNode* ptr = &dummy;
for (int n : nums) {
ptr->next = new ListNode(n);
ptr = ptr->next;
}
return dummy.next;
}
};
// Two pointers
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
while (slow != nullptr && fast != nullptr) {
if (fast->next == nullptr) {
break;
}
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};
TEST(Solution, middleNode) {
std::vector<std::pair<ListNode*, int>> cases = {
std::make_pair(ListNode::convert(std::vector<int>{1, 2, 3, 4, 5}), 3),
std::make_pair(ListNode::convert(std::vector<int>{1, 2, 3, 4, 5, 6}), 4),
};
for (auto& c : cases) {
EXPECT_EQ(Solution().middleNode(c.first)->val, c.second);
}
}